首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Android之使用JavaMail发送邮件

Android之使用JavaMail发送邮件

作者头像
forrestlin
发布于 2018-05-23 09:41:35
发布于 2018-05-23 09:41:35
1.3K0
举报
文章被收录于专栏:蜉蝣禅修之道蜉蝣禅修之道

            首先,我们原本可以直接通过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包导入构建路径

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2012年12月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Java-工具类之发送邮件
代码已托管到 https://github.com/yangshangwei/commonUtils
小小工匠
2021/08/17
1.8K0
邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件
该文章介绍了如何通过JavaMailSender发送邮件,并附带上图片和附件。同时,介绍了MailReceiver实现接收邮件。
IT可乐
2018/01/04
3.6K0
邮件实现详解(四)------JavaMail 发送(带图片和附件)和接收邮件
使用 JavaMail 实现邮件发送与收取
因为上一篇已经实现了James的配置,那接下来就是利用javaMail实现邮件的发送和收取。
林老师带你学编程
2022/11/30
1.1K0
java发送邮件-模板
今天写完了一个关于使用模板发送邮件的代码,作为例子保存着,希望以后用得着,也希望能够帮助到需要帮助的人 以163网易邮箱为例,使用java发送邮件,发送以邮件时使用模板(.ftl文件转换为html)发送邮件内容,并附带上附件,可抄送给多个人。项目的结构目录如下
全栈程序员站长
2022/08/28
1.9K0
java发送邮件-模板
Java发送邮件工具类
这是从根据从码云上找到的一个邮件发送开源项目进行了一定的修改后 这里用的是Spring Boot项目进行的测试 项目结构: pom文件需要引入以下三个jar包: <dependency
二十三年蝉
2018/04/10
3K0
Java发送邮件工具类
基于smtp协议的邮件系统(自己写的)
最近几天做好了应用【贱泰迪】,其中有个意见反馈,发送邮件, 我知道可以调用系统发送邮件,但这种方法有个弊端,就是您的手机必须安装Mail的客户端, 因此我想不用系统发送邮件这种方式,能不能向任意邮
xiangzhihong
2018/01/26
2.9K0
使用JavaMail发送邮件
  我们在实际开发中,常常会遇到需要使用java代码进行发送邮件的需求,我们可以通过这种方式向用户推送通知等。
阿豪聊干货
2018/08/09
8740
SpringBoot集成QQ/网易/Gmail邮箱发送邮件
添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> application.yml配置文件新增 spring: mail: # qq host: smtp.qq.com #发送邮件服务器 username: xx@qq.com #QQ邮箱 password:
高大北
2022/12/27
1.6K0
java发送邮件带url、html
此类邮件URL需要做校验,如果链接中只包含一个标示,则只对当前标示加密,如果所有参数都暴露在地址栏中可以将所有参数拼起来用MD5或者其他方式加密后存放在该URL中,例如为validateCode,此次也要对validateCode的值做encode转换,不然特殊符号在URL中会自动转换,之后只对validateCode校验即可知道该链接是否正确。
全栈程序员站长
2022/08/28
1.5K0
java发送邮件带url、html
Java定时发送邮件
刚开始计划指定几个同事轮流发送,业务只要不被攻击一般是没有问题的。但是想一想休息日还要处理工作上的事情(非紧急的)就不爽,近几年一直在做前端的事情,后台碰的少,毕竟也接触过,所以决定搞一个定时发送邮件的程序,遂上网查找资料。
Jack Chen
2019/09/23
2.1K0
Java定时发送邮件
java之jmail实现邮件发送
https://zhidao.baidu.com/question/1431992442917304139.html
周杰伦本人
2023/10/12
3290
java之jmail实现邮件发送
【Java】邮件Demo(SSL加密传输)
温馨提示:本文最后更新于2021-11-18,若文件或内容有错误或已失效,请在下方留言。
NorthS
2023/03/21
8220
java 发邮件 代码
​1. MailSenderInfo package org.fh.util.mail; /** * 说明:发送邮件需要使用的基本信息 * 作者:FH Admin * fhadmin.org */ import java.util.Properties; public class MailSenderInfo { // 发送邮件的服务器的IP和端口 private String mailServerHost; private Stri
FHAdmin
2021/06/23
2.1K0
Java发送邮件(含附件)
前几天写了一个Java发送邮件的帮助类i,可以发送QQ和163的邮箱,也可以发送附件,写个一个主要的方法,其他的可以自己封装。代码如下:
付威
2020/01/21
1.6K0
【Email】Java发送邮件接口与配置类
可能最近写博客时间不会很多,最近又在搞一个项目了。 发送邮件的类,我以前写过,不过写的不是接口封装的,现在自己项目用到了,就重新写了一下,现在把它分享出来给大家。
谙忆
2021/01/21
7050
【Email】Java发送邮件接口与配置类
java发送邮件功能,以发送qq邮件为例
问题①: java发送qq邮件出现如下错误的解决方法:      503 Error: need EHLO and AUTH first ! pop.put("mail.smtp.auth", "true");//注意value值不能不设置,并且不能是Boolean类型,应为字符串,否则会报如上所示错误 问题②: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1 原因:     465端口是为SMTPS(SMTP-ove
用户1215919
2018/02/27
2.1K0
JavaMail 邮件发送,有意思的附件名乱码 → 客户端正常,web端乱码
  基于 JavaMail 1.5.5 ,实现了邮件发送功能,也对接了一些客户,没出现什么问题
青石路
2023/03/09
2.9K0
JavaMail 邮件发送,有意思的附件名乱码 → 客户端正常,web端乱码
爬虫获取邮箱,存入数据库,发送邮件java Mail
在网页上获取邮箱: package com.my.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Statement; import java.util.regex.Matcher; import java.util.regex.Pattern; public clas
JQ实验室
2022/02/09
1.5K0
带附件/密送/抄送的 javaMail 邮件发送 -- java_demo(两种实现方式)
javaMail 的邮件发送包括了抄送(CC),密送(BCC)采用springBoot
allsmallpig
2021/02/25
1.7K0
SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件
发送模板邮件使用的方法与发送HTML邮件的方法一致。只是发送邮件时使用到的模板引擎,这里使用的模板引擎为Thymeleaf。
Javen
2018/08/21
3.1K0
SpringBoot 2.x 集成QQ邮箱、网易系邮箱、Gmail邮箱发送邮件
推荐阅读
相关推荐
Java-工具类之发送邮件
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档