服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android使用Javamail发送Email群发加附件

Android使用Javamail发送Email群发加附件

2022-09-19 17:59拳四郎 Android

这篇文章主要为大家详细介绍了Android使用Javamail发送Email群发加附件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

之前写了一篇关于android中发送email的文章,里面用到的是隐式的intent来激活系统自带的邮件发送功能。

今天花了一天来自己实现这个邮件发送功能。

这里用gmail作为发送方的邮箱,其他网易,新浪什么的应该也ok,qq貌似不行。

下面是实现步骤及相关代码。

项目添加jar包

将activation.jar,additionnal.jar,mail.jar放到项目的libs 文件夹。然后在项目中选中这三个包,右击->build path->add to buildpath.

添加成功后项目就像这样.

Android使用Javamail发送Email群发加附件

项目中添加mail类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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调用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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异常。

布局文件

主界面的布局文件,非常简单。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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>

运行效果图:

Android使用Javamail发送Email群发加附件

点击发送后

Android使用Javamail发送Email群发加附件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/silangquan/article/details/8774362

延伸 · 阅读

精彩推荐