当前位置:   article > 正文

Android下发送邮件功能总结_android 使用commons-net-3.3.jar

android 使用commons-net-3.3.jar

最近项目用到邮件发送功能,自然联想到掉起手机自带的邮件APK,但太过于依赖于系统的邮件apk,如何你需要默默后台发送邮件,这种功能显然是无法满足的,经过查阅资料基本可以找到两种现有的解决方案。


1、第一种使用commons-net-3.3.jar

此jar可以实现简单的邮件发送,如果你只需要发送简单的文本邮件,这个包就可以满足需求。这个包封装的还是比较好的,监听接口等都很完善,使用也非常方便,唯一的缺点就是不支持附件、HTML等方式发送邮件,除非自己去扩展这个包,根据SMTP协议实现图片、附件、HTML邮件。


当然这个包还有其他功能,封装了很多协议,具体如下:

  • FTP/FTPS
  • FTP over HTTP (experimental)
  • NNTP
  • SMTP(S)
  • POP3(S)
  • IMAP(S)
  • Telnet
  • TFTP
  • Finger
  • Whois
  • rexec/rcmd/rlogin
  • Time (rdate) and Daytime
  • Echo
  • Discard
  • NTP/SNTP
具体实现可以看下面我附的代码,注意还需要使用apache mime4j编码一下邮件的中文部分,不然显示乱码。


2、使用mail.jar核心邮件包实现邮件发送功能

可支持附件、图片、HTML等邮件形式,使用这个包需要引入activation.jar、additionnal.jar,这样就可以实现带有附件的邮件发送了,这才是我们真正需要的,一般来说不能发送附件还是比较鸡肋的,当然这个mail.jar使用起来不是那么顺畅,所以apache有一个再次封装的包commons-email-1.4.jar,使用这个包发送邮件就非常简单了。


我已经写了一个DEMO,正式项目已经将本代码重构,这是一个测试DEMO,稍作修改就可以用于项目了。已经调试通过可正常发送邮件。

下面是界面,抄送和密送没有写入,需要你自己加入,具体可以参照Apache官网的对应包的API http://commons.apache.org/


当然第一步你需要向sd卡push 一张png图片(pdf02.png),如果你也是使用genymotion 模拟器可以使用如下方式将图片添加到sd 卡


然后点击界面发送后,logcat 会显示如下信息表示发送成功。


好了,到发件邮箱看看是不是有相应的邮件发出了!


好了,一切Ok!具体核心代码如下:

  1. package com.example.email;
  2. import java.io.File;
  3. import java.io.Writer;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. import org.apache.commons.mail.EmailAttachment;
  7. import org.apache.commons.mail.EmailException;
  8. import org.apache.commons.mail.MultiPartEmail;
  9. import org.apache.commons.net.ProtocolCommandEvent;
  10. import org.apache.commons.net.ProtocolCommandListener;
  11. import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
  12. import org.apache.commons.net.smtp.SMTPClient;
  13. import org.apache.commons.net.smtp.SMTPReply;
  14. import org.apache.commons.net.smtp.SimpleSMTPHeader;
  15. import org.apache.james.mime4j.codec.EncoderUtil;
  16. import org.apache.james.mime4j.codec.EncoderUtil.Usage;
  17. import android.app.Activity;
  18. import android.app.Fragment;
  19. import android.os.AsyncTask;
  20. import android.os.Bundle;
  21. import android.os.Environment;
  22. import android.view.LayoutInflater;
  23. import android.view.Menu;
  24. import android.view.MenuItem;
  25. import android.view.View;
  26. import android.view.View.OnClickListener;
  27. import android.view.ViewGroup;
  28. import android.widget.Button;
  29. import android.widget.EditText;
  30. public class MainActivity extends Activity {
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_main);
  35. if (savedInstanceState == null) {
  36. getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
  37. }
  38. }
  39. @Override
  40. public boolean onCreateOptionsMenu(Menu menu) {
  41. // Inflate the menu; this adds items to the action bar if it is present.
  42. getMenuInflater().inflate(R.menu.main, menu);
  43. return true;
  44. }
  45. @Override
  46. public boolean onOptionsItemSelected(MenuItem item) {
  47. // Handle action bar item clicks here. The action bar will
  48. // automatically handle clicks on the Home/Up button, so long
  49. // as you specify a parent activity in AndroidManifest.xml.
  50. int id = item.getItemId();
  51. if (id == R.id.action_settings) {
  52. return true;
  53. }
  54. return super.onOptionsItemSelected(item);
  55. }
  56. /**
  57. * A placeholder fragment containing a simple view.
  58. */
  59. public static class PlaceholderFragment extends Fragment {
  60. private EditText et_receive, et_cc, et_bcc, et_send, et_pwd, et_subject, et_message;
  61. private Button btn_send;
  62. public PlaceholderFragment() {
  63. }
  64. @Override
  65. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  66. View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  67. btn_send = (Button) rootView.findViewById(R.id.btn_send);
  68. et_receive = (EditText) rootView.findViewById(R.id.et_receive);
  69. et_cc = (EditText) rootView.findViewById(R.id.et_cc);
  70. et_bcc = (EditText) rootView.findViewById(R.id.et_bcc);
  71. et_send = (EditText) rootView.findViewById(R.id.et_send);
  72. et_pwd = (EditText) rootView.findViewById(R.id.et_password);
  73. et_subject = (EditText) rootView.findViewById(R.id.et_subject);
  74. et_message = (EditText) rootView.findViewById(R.id.et_message);
  75. setListener();
  76. return rootView;
  77. }
  78. private void setListener() {
  79. btn_send.setOnClickListener(new OnClickListener() {
  80. @Override
  81. public void onClick(View v) {
  82. final String receive = et_receive.getText().toString().trim();
  83. final String cc = et_cc.getText().toString().trim();
  84. final String bcc = et_bcc.getText().toString().trim();
  85. final String send = et_send.getText().toString().trim();
  86. final String pwd = et_pwd.getText().toString().trim();
  87. final String subject = et_subject.getText().toString().trim();
  88. final String message = et_message.getText().toString().trim();
  89. // 建立发送邮件任务
  90. new AsyncTask<String, Integer, Boolean>() {
  91. @Override
  92. protected Boolean doInBackground(String... params) {
  93. try {
  94. // sendEmailByApacheCommonsNet(send, pwd,
  95. // receive, subject, message);
  96. System.out.println("send=" + send + ",pwd=" + pwd + ",receive=" + receive + ",subject=" + subject + ",message="
  97. + message);
  98. sendEmailByApacheCommonsEmail(send, pwd, receive, subject, message);
  99. return true;
  100. } catch (Exception e) {
  101. e.printStackTrace();
  102. return false;
  103. }
  104. }
  105. }.execute();
  106. }
  107. });
  108. }
  109. /**
  110. * 检测邮箱地址是否合法
  111. *
  112. * @param address
  113. * @return true合法 false不合法
  114. */
  115. private boolean verifyEmailAddress(String address) {
  116. if (null == address || "".equals(address))
  117. return false;
  118. Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");// 复杂匹配
  119. Matcher m = p.matcher(address);
  120. return m.matches();
  121. }
  122. /**
  123. * @Description TODO 发送带附件的email
  124. * @throws EmailException
  125. */
  126. private void sendEmailByApacheCommonsEmail(String from, String fromPwd, String to, String subject, String message) throws EmailException {
  127. if (!verifyEmailAddress(from) || !verifyEmailAddress(to)) {
  128. System.out.println("enter verifyEmailAddress");
  129. return;
  130. }
  131. // Create the attachment
  132. EmailAttachment attachment = new EmailAttachment();
  133. attachment.setPath(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "pdf02.png");
  134. attachment.setDisposition(EmailAttachment.ATTACHMENT);
  135. attachment.setDescription("pdf02");
  136. attachment.setName("pdf02.png");
  137. // Create the email message
  138. MultiPartEmail email = new MultiPartEmail();
  139. email.setDebug(true);
  140. // 这里使用163邮箱服务器,实际需要修改为对应邮箱服务器
  141. email.setHostName("smtp.163.com");
  142. email.setSmtpPort(25);
  143. email.setSocketTimeout(6 * 1000);
  144. email.setCharset("UTF-8");
  145. email.setAuthentication(from, fromPwd);
  146. email.addTo(to, to);
  147. // email.addBcc(arg0);
  148. // email.addCc(arg0);
  149. email.setFrom(from, from);
  150. email.setSubject(subject);
  151. email.setMsg(message);
  152. // add the attachment
  153. email.attach(attachment);
  154. // send the email
  155. String sendStr = email.send();
  156. System.out.println("sendStr=" + sendStr);
  157. }
  158. /**
  159. * @Description TODO 只能发送简单的邮件文本,如需要发送附件需要自己去实现
  160. * @throws Exception
  161. */
  162. @SuppressWarnings("unused")
  163. private void sendEmailByApacheCommonsNet(String from, String fromPwd, String to, String subject, String message) throws Exception {
  164. if (!verifyEmailAddress(from) || !verifyEmailAddress(to)) {
  165. System.out.println("enter verifyEmailAddress");
  166. return;
  167. }
  168. String hostname = "smtp.163.com";
  169. int port = 25;
  170. String password = fromPwd;
  171. String login = from;
  172. String text = message;
  173. AuthenticatingSMTPClient client = new AuthenticatingSMTPClient();
  174. try {
  175. // optionally set a timeout to have a faster feedback on errors
  176. client.setDefaultTimeout(10 * 6000);
  177. // you connect to the SMTP server
  178. client.connect(hostname, port);
  179. client.addProtocolCommandListener(new ProtocolCommandListener() {
  180. @Override
  181. public void protocolCommandSent(ProtocolCommandEvent arg0) {
  182. System.out.println("protocolCommandSent =" + arg0.getCommand());
  183. }
  184. @Override
  185. public void protocolReplyReceived(ProtocolCommandEvent arg0) {
  186. System.out.println("protocolReplyReceived =" + arg0.getMessage());
  187. }
  188. });
  189. // you say ehlo and you specify the host you are connecting
  190. // from, could be anything
  191. client.ehlo("163");
  192. // if your host accepts STARTTLS, we're good everything will be
  193. // encrypted, otherwise we're done here
  194. if (client.execTLS()) {
  195. System.out.println("enter to login");
  196. client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
  197. checkReply(client);
  198. client.setSender(from);
  199. checkReply(client);
  200. client.addRecipient(to);
  201. checkReply(client);
  202. Writer writer = client.sendMessageData();
  203. if (writer != null) {
  204. // 使用apache mime4j中的EncoderUtil来编码邮件主题
  205. String encodedSubject = EncoderUtil.encodeIfNecessary(subject, Usage.TEXT_TOKEN, 0);
  206. SimpleSMTPHeader header = new SimpleSMTPHeader(from, to, encodedSubject);
  207. header.addHeaderField("Content-Type", "text/plain; charset=UTF-8");
  208. header.addHeaderField("Content-Transfer-Encoding", "base64");
  209. // 使用apache mime4j中的EncoderUtil来编码邮件正文
  210. String encodedBody = EncoderUtil.encodeB(text.getBytes());
  211. writer.write(header.toString());
  212. writer.write(encodedBody);
  213. writer.close();
  214. if (!client.completePendingCommand()) {// failure
  215. throw new Exception("Failure to send the email ");
  216. }
  217. } else {
  218. throw new Exception("Failure to send the email ");
  219. }
  220. } else {
  221. throw new Exception("STARTTLS was not accepted ");
  222. }
  223. } catch (Exception e) {
  224. throw e;
  225. } finally {
  226. client.logout();
  227. client.disconnect();
  228. }
  229. }
  230. private static void checkReply(SMTPClient sc) throws Exception {
  231. if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
  232. throw new Exception("Transient SMTP error ");
  233. } else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
  234. throw new Exception("Permanent SMTP error ");
  235. }
  236. }
  237. }
  238. }

3、DEMO下载

点此下载

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/196178
推荐阅读