Android使用Javamail发送Email群发加附件
程序员文章站
2022-06-23 15:05:36
之前写了一篇关于android中发送email的文章,里面用到的是隐式的intent来激活系统自带的邮件发送功能。
今天花了一天来自己实现这个邮件发送功能。
这里用gm...
之前写了一篇关于android中发送email的文章,里面用到的是隐式的intent来激活系统自带的邮件发送功能。
今天花了一天来自己实现这个邮件发送功能。
这里用gmail作为发送方的邮箱,其他网易,新浪什么的应该也ok,qq貌似不行。
下面是实现步骤及相关代码。
项目添加jar包
将activation.jar,additionnal.jar,mail.jar放到项目的libs 文件夹。然后在项目中选中这三个包,右击->build path->add to buildpath.
添加成功后项目就像这样.
项目中添加mail类
package com.example.mailtest; import java.util.date; import java.util.properties; import javax.activation.commandmap; import javax.activation.datahandler; import javax.activation.datasource; import javax.activation.filedatasource; import javax.activation.mailcapcommandmap; import javax.mail.bodypart; import javax.mail.multipart; import javax.mail.passwordauthentication; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.internetaddress; import javax.mail.internet.mimebodypart; import javax.mail.internet.mimemessage; import javax.mail.internet.mimemultipart; public class mail extends javax.mail.authenticator { private string _user; private string _pass; private string[] _to; private string _from; private string _port; private string _sport; private string _host; private string _subject; private string _body; private boolean _auth; private boolean _debuggable; private multipart _multipart; public mail() { _host = "smtp.gmail.com"; // default smtp server _port = "465"; // default smtp port _sport = "465"; // default socketfactory port _user = ""; // username _pass = ""; // password _from = ""; // email sent from _subject = ""; // email subject _body = ""; // email body _debuggable = false; // debug mode on or off - default off _auth = true; // smtp authentication - default on _multipart = new mimemultipart(); // there is something wrong with mailcap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. mailcapcommandmap mc = (mailcapcommandmap) commandmap.getdefaultcommandmap(); mc.addmailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addmailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addmailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addmailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addmailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); commandmap.setdefaultcommandmap(mc); } public mail(string user, string pass) { this(); _user = user; _pass = pass; } public void setto(string[] toarr) { this._to = toarr; } public void setfrom(string string) { this._from = string; } public void setsubject(string string) { this._subject = string; } public boolean send() throws exception { properties props = _setproperties(); if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { session session = session.getinstance(props, this); mimemessage msg = new mimemessage(session); msg.setfrom(new internetaddress(_from)); internetaddress[] addressto = new internetaddress[_to.length]; for (int i = 0; i < _to.length; i++) { addressto[i] = new internetaddress(_to[i]); } msg.setrecipients(mimemessage.recipienttype.to, addressto); msg.setsubject(_subject); msg.setsentdate(new date()); // setup message body bodypart messagebodypart = new mimebodypart(); messagebodypart.settext(_body); _multipart.addbodypart(messagebodypart); // put parts in message msg.setcontent(_multipart); // send email transport.send(msg); return true; } else { return false; } } public void addattachment(string filename) throws exception { bodypart messagebodypart = new mimebodypart(); datasource source = new filedatasource(filename); messagebodypart.setdatahandler(new datahandler(source)); messagebodypart.setfilename(filename); _multipart.addbodypart(messagebodypart); } @override public passwordauthentication getpasswordauthentication() { return new passwordauthentication(_user, _pass); } private properties _setproperties() { properties props = new properties(); props.put("mail.smtp.host", _host); if(_debuggable) { props.put("mail.debug", "true"); } if(_auth) { props.put("mail.smtp.auth", "true"); } props.put("mail.smtp.port", _port); props.put("mail.smtp.socketfactory.port", _sport); props.put("mail.smtp.socketfactory.class", "javax.net.ssl.sslsocketfactory"); props.put("mail.smtp.socketfactory.fallback", "false"); return props; } // the getters and setters public string getbody() { return _body; } public void setbody(string _body) { this._body = _body; } // more of the getters and setters ….. }
mailactivity调用
package com.example.mailtest; import java.util.properties; import javax.mail.address; import javax.mail.message; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; import android.os.asynctask; import android.os.bundle; import android.os.handler; import android.app.activity; import android.app.progressdialog; import android.util.log; import android.view.menu; import android.view.view; import android.widget.button; import android.widget.toast; public class mailactivity extends activity { private button sendbtn; private string username; private string password; private handler sendhandler; private progressdialog progressdialog; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_mail); sendbtn=(button)findviewbyid(r.id.btnsend); sendhandler = new handler(); sendbtn.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { sendtask stask = new sendtask(); stask.execute(); } }); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater().inflate(r.menu.activity_mail, menu); return true; } class sendtask extends asynctask<integer, integer, string>{ //后面尖括号内分别是参数(例子里是线程休息时间),进度(publishprogress用到),返回值 类型 @override protected void onpreexecute() { //第一个执行方法 toast.maketext(getapplicationcontext(), "begin send!", toast.length_short).show(); super.onpreexecute(); } @override protected string doinbackground(integer... params) { //第二个执行方法,onpreexecute()执行完后执行 // todo auto-generated method stub mail m = new mail("empty.shen@gmail.com", "*****"); string[] toarr = {"silangquan@gmail.com","k283228391@126.com"}; m.setto(toarr); m.setfrom("wooo@wooo.com"); m.setsubject("javamailtest"); m.setbody("email body."); try { //if you want add attachment use function addattachment. //m.addattachment("/sdcard/filelocation"); if(m.send()) { system.out.println("email was sent successfully."); } else { system.out.println("email was not sent."); } } catch(exception e) { //toast.maketext(mailapp.this, "there was a problem sending the email.", toast.length_long).show(); log.e("mailapp", "could not send email", e); } return ""; } @override protected void onprogressupdate(integer... progress) { //这个函数在doinbackground调用publishprogress时触发,虽然调用时只有一个参数 //但是这里取到的是一个数组,所以要用progesss[0]来取值 //第n个参数就用progress[n]来取值 super.onprogressupdate(progress); } @override protected void onpostexecute(string r) { //doinbackground返回时触发,换句话说,就是doinbackground执行完后触发 //这里的result就是上面doinbackground执行后的返回值,所以这里是"执行完毕" //settitle(result); super.onpostexecute(r); } } }
这里用到了asynctask,应为直接在ui线程中连接互联网的话,或爆 android.os.networkonmainthreadexception异常。
布局文件
主界面的布局文件,非常简单。
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".mailactivity" > <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:text="@string/hello_world" /> <button android:id="@+id/btnsend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:layout_margintop="19dp" android:text="send" /> </relativelayout>
运行效果图:
点击发送后
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。