Android之使用JavaMail发送邮件

            首先,我们原本可以直接通过Intent来调用系统邮件客户端发送邮件,但是这种发送需要跳转activity很不方便,所以我打算自己通过smtp协议发送邮件。很幸运,在google code上有一个现成的javaMail的java邮件客户端,我们只需要调用其中的接口就可以了。下面放出使用javaMail的一个demo源代码。

1.自己封装一个邮件发送类MailSender。

public class MailSender extends Authenticator { private String user; private String password; private Session session; private String mailhost = "smtp.gmail.com";//默认用gmail发送 private Multipart messageMultipart; private Properties properties; static { Security.addProvider(new JSSEProvider()); } public MailSender(String user, String password) { this.user = user; this.password = password; properties = new Properties(); properties.setProperty("mail.transport.protocol", "smtp"); properties.setProperty("mail.host", mailhost); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.quitwait", "false"); session = Session.getDefaultInstance(properties, this); messageMultipart=new MimeMultipart(); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } public synchronized void sendMail(String subject, String body, String sender, String recipients,String attachment) throws Exception { MimeMessage message = new MimeMessage(session); message.setSender(new InternetAddress(sender));//邮件发件人 message.setSubject(subject);//邮件主题 //设置邮件内容 BodyPart bodyPart=new MimeBodyPart(); bodyPart.setText(body); messageMultipart.addBodyPart(bodyPart); // message.setDataHandler(handler); //设置邮件附件 if(attachment!=null){ DataSource dataSource=new FileDataSource(attachment); DataHandler dataHandler=new DataHandler(dataSource); bodyPart.setDataHandler(dataHandler); bodyPart.setFileName(attachment.substring(attachment.lastIndexOf("/")+1)); } message.setContent(messageMultipart); if (recipients.indexOf(',') > 0) //多个联系人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else //单个联系人 message.setRecipient(Message.RecipientType.TO, new InternetAddress( recipients)); Transport.send(message); } //继承DataSource设置字符编码 public class ByteArrayDataSource implements DataSource { private byte[] data; private String type; public ByteArrayDataSource(byte[] data, String type) { super(); this.data = data; this.type = type; } public ByteArrayDataSource(byte[] data) { super(); this.data = data; } public void setType(String type) { this.type = type; } public String getContentType() { if (type == null) return "application/octet-stream"; else return type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Not Supported"); } public PrintWriter getLogWriter() throws SQLException { // TODO Auto-generated method stub return null; } public int getLoginTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } public void setLogWriter(PrintWriter out) throws SQLException { // TODO Auto-generated method stub } public void setLoginTimeout(int seconds) throws SQLException { // TODO Auto-generated method stub } public boolean isWrapperFor(Class<?> arg0) throws SQLException { // TODO Auto-generated method stub return false; } public <T> T unwrap(Class<T> arg0) throws SQLException { // TODO Auto-generated method stub return null; } public Connection getConnection() throws SQLException { // TODO Auto-generated method stub return null; } public Connection getConnection(String theUsername, String thePassword) throws SQLException { // TODO Auto-generated method stub return null; } } public String getMailhost() { return mailhost; } public void setMailhost(String mailhost) { this.mailhost = mailhost; properties.setProperty("mail.host", this.mailhost); } }

2.JSSE将帮助处理TLS和SSL业务

public class JSSEProvider extends Provider { public JSSEProvider() {         super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");         AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {             public Void run() {                 put("SSLContext.TLS",                         "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");                 put("Alg.Alias.SSLContext.TLSv1", "TLS");                 put("KeyManagerFactory.X509",                         "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");                 put("TrustManagerFactory.X509",                         "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");                 return null;             }         });     } }

3.主activity调用邮件发送类

public class MainActivity extends Activity { private Button sendButton = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendButton = (Button) this.findViewById(R.id.send_btn); sendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub SenderRunnable senderRunnable = new SenderRunnable( "xxxxxxx@163.com", "xxxxxxxx"); senderRunnable.setMail("this is the test subject", "this is the test body", "xxxxxxxxx@gmail.com","/mnt/sdcard/test.txt"); new Thread(senderRunnable).start(); } }); } public boolean onCreateOptionsMenu(Menu menu) { } //android3.2不允许主线程通信 class SenderRunnable implements Runnable { private String user; private String password; private String subject; private String body; private String receiver; private MailSender sender; private String attachment; public SenderRunnable(String user, String password) { this.user = user; this.password = password; sender = new MailSender(user, password); String mailhost=user.substring(user.lastIndexOf("@")+1, user.lastIndexOf(".")); if(!mailhost.equals("gmail")){ mailhost="smtp."+mailhost+".com"; Log.i("hello", mailhost); sender.setMailhost(mailhost); } } public void setMail(String subject, String body, String receiver,String attachment) { this.subject = subject; this.body = body; this.receiver = receiver; this.attachment=attachment; } public void run() { // TODO Auto-generated method stub try { sender.sendMail(subject, body, user, receiver,attachment); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

项目全部源码下载地址:http://download.csdn.net/detail/xanxus46/4888658

javaMail地址:http://code.google.com/p/javamail-android/,使用时记得把三个jar包导入构建路径

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏猿份到

浅谈Retrofit 源码

现在的项目界面都是按iOS的风格,虽然界面无法发挥出我们大Android的风格,网络框架动不动就是mvp+ okhttp +retrofit+rxjava,m...

3668
来自专栏Golang语言社区

Go 语言 数据库操作之插入数据实现

代码非复制可以用,因为有些是没有提交,例如打印日志;总的来说,思路重要。 例子源码 如下: // 插入意见反馈的意见 func XiaoFFeedBackFu...

2815
来自专栏码匠的流水账

聊聊spring cloud gateway的SetStatusGatewayFilter

本文主要研究下spring cloud gateway的SetStatusGatewayFilter

1331
来自专栏androidBlog

Android 自定义 MarqueeView 实现跑马灯 —— 原理篇

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gdutxiaoxu/article/details/...

1801
来自专栏Android常用基础

简单好用的RecyclerView适配器

给大家推荐个好用RecyclerView适配器,也就是在百篮应用里用到的适配器。为了大家学习方便,这里简单的写下如何使用这个适配器,不做代码具体的分析,有兴趣的...

1353
来自专栏何俊林

Android支付实践(二)之微信支付详解与Demo

前言:集成支持宝和微信支付,是公司获取收益的最主要的部分,这两大巨头几乎在支付业务上不可或缺,今天看下Simon_Crystin独家授权本公众号发步的Andro...

2416
来自专栏cloudskyme

大话企业级android读书笔记(三)

android中的数据存储类型包括:内存,普通文件,Shared Preferences,XML和SQLLite等 文件操作: 包括读写 /** * 【文件操...

3726
来自专栏Android先生

Android 使用代码实现一个选词(拖拽)填空题

在上一篇文章《Android 使用代码实现一个填空题》中,我们学习了如何实现一个填空题,今天继续接着上一篇文章的节奏,学习一下如何实现一个选词填空题,由于本文中...

1102
来自专栏向治洪

android异步操作

为了使UI在数据获取时不僵死,数据获取需要在新开Worker线程中进行,然后将返回结果在UI线程中进行读取并渲染页面。面对这种异步处理,到底如何写才简洁,先后面...

2278
来自专栏求索之路

MVVM架构之自动增删改的极简RecycleView的实现

介绍图 先上个源代码的链接:https://github.com/whenSunSet/MVVMRecycleView RecycleView是Google替...

4106

扫码关注云+社区

领取腾讯云代金券