在Android开发中,邮件发送一般常用两种方式,一种是调用系统的邮箱来放,另一种是自己去编程实现邮件的发送,第一种方式比较简单,通过Intent的隐式意图去打开系统的邮箱,并通过intent的传值指定收件人(抄送、密送等)、主题和内容,这个比较简单,这里就不再介绍,主要是介绍一下第二种方法,即自己定义邮件发送的工具类。
一、创建邮件实体类(这里我们首先导入activation.jar、additionnal.jar和mail.jar这几个jar包,网上都能搜到,这里就不再上传了)
/**
* 邮件信息实体类
*/
public class MailInfo {
private boolean isValidate; // 是否需要验证身份
private String userName; // 发件人邮箱用户名
private String password; // 发件人邮箱密码
private String mailServerHost; // 发送邮件的服务器的IP
private String mailServerPort; // 发送邮件的服务器的端口
private String fromAddress; // 发件人地址
private String toAddress; // 收件人地址
private String copyAddress; // 抄送人地址
private String mailSubject; // 邮件主题
private String mailContent; // 邮件内容
private String attachment; // 邮件附件
...//getter和setter方法
}
二、身份验证
在发送邮件之前需要验证发件人的身份信息,自定义类继承Authenticator类,构造方法中传入发件人用户名和密码,并实现其protected PasswordAuthentication getPasswordAuthentication()方法,这里需要注意的是,这个方法不能自己修改,方法名什么的不能随意修改,否则会验证失败,以下是代码:
public class UserAuthenticator extends Authenticator {
private String userName;
private String password;
public UserAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(this.userName, this.password);
}
}
三、这一步是关键,我们需要创建邮件的会话属性、进行身份验证、创建邮件消息等,我们分开步骤来说(这里以163邮箱为例);
获取邮件的会话属性:
Properties properties = new Properties();
properties.put("mail.smtp.host", mailInfo.getMailServerHost());
properties.put("mail.smtp.port", mailInfo.getMailServerPort());
properties.put("mail.smtp.auth", mailInfo.isValidate() ? "true" : "false");
身份验证,这里我们需要将邮件实体类中的isValidate这个属性设置为true,发送邮件时会首先验证我们的发件人信息是否正确,如果身份验证失败,则后面的发送无法进行;
UserAuthenticator userAuthenticator = null;
// 判断是否需要身份验证
if(mailInfo.isValidate()) {
userAuthenticator = new UserAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
接下来是根据邮件会话属性和密码验证器构造一个发送邮件的session,创建邮件信息并且进行连接;
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(properties, userAuthenticator);
session.setDebug(true);
// 根据session创建一个邮件消息
Message message = new MimeMessage(session);
try {
Address fromAddress = new InternetAddress(mailInfo.getFromAddress(), mailInfo.getFromAddress().substring(0, mailInfo.getFromAddress().indexOf("@")));
Address toAddress = new InternetAddress(mailInfo.getToAddress(), "to");
// Address copyAddress = new InternetAddress(mailInfo.getCopyAddress(), "copy");
message.setSubject(mailInfo.getMailSubject());
// 将邮件内容添加到邮件消息中,仅适用于文本内容
// String mailcontent = mailInfo.getMailContent();
// message.setText(mailcontent);
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getMailContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
message.setContent(mainPart);
message.setSubject(mailInfo.getMailSubject());
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(mailInfo.getMailServerHost(), mailInfo.getUserName(), mailInfo.getPassword());
Transport.send(message);
transport.close();
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以下是整个邮件发送工具类的完整代码:
public class MailSendReceiverUtil {
/**
* 发送邮件
*
* @param mailInfo 邮件信息
* @return 是否发送成功
*/
public boolean sendMail(MailInfo mailInfo) {
// 获取邮件会话属性
Properties properties = new Properties();
properties.put("mail.smtp.host", mailInfo.getMailServerHost());
properties.put("mail.smtp.port", mailInfo.getMailServerPort());
properties.put("mail.smtp.auth", mailInfo.isValidate() ? "true" : "false");
UserAuthenticator userAuthenticator = null;
// 判断是否需要身份验证
if(mailInfo.isValidate()) {
userAuthenticator = new UserAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(properties, userAuthenticator);
session.setDebug(true);
// 根据session创建一个邮件消息
Message message = new MimeMessage(session);
try {
Address fromAddress = new InternetAddress(mailInfo.getFromAddress(), mailInfo.getFromAddress().substring(0, mailInfo.getFromAddress().indexOf("@")));
Address toAddress = new InternetAddress(mailInfo.getToAddress(), "to");
// Address copyAddress = new InternetAddress(mailInfo.getCopyAddress(), "copy");
message.setSubject(mailInfo.getMailSubject());
// 将邮件内容添加到邮件消息中,仅适用于文本内容
// String mailcontent = mailInfo.getMailContent();
// message.setText(mailcontent);
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
html.setContent(mailInfo.getMailContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
message.setContent(mainPart);
message.setSubject(mailInfo.getMailSubject());
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(mailInfo.getMailServerHost(), mailInfo.getUserName(), mailInfo.getPassword());
Transport.send(message);
transport.close();
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
四、最后在程序主函数中实例化邮件实体,并设置发件人详细信息,开启线程去发送邮件;
private void setData() {
// TODO Auto-generated method stub
mailInfo = new MailInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("*****");//邮箱用户名
mailInfo.setPassword("*****");//邮箱密码
mailInfo.setFromAddress("*****@163.com");//发件人的邮箱地址
mailInfo.setToAddress("*****@qq.com");//收件人的邮箱地址
mailInfo.setMailSubject("title");
mailInfo.setMailContent("mailContent");
}
这里有几点是需要注意的,关于邮箱发件人信息的验证,当时我在测试的时候,身份验证总是出现问题,网上查了好多没有解决,后来自己发现了问题,
· 邮箱的用户名,用户名跟地址的区别,例如你的邮箱地址时 name@163,com,那么用户名是@之前的内容;
· 在邮箱中需要设置SMTP端口打开,否则也是无法发送的;
· 还有一个就是在邮箱中是否设置了第三方平台登录时的独立密码(当时我就是这个问题,设置了其他地方登录邮箱的独立密码,然后使用邮箱密码登录一直提示身份 验证失败,这个需要注意一下)
发送邮件
MailSendReceiverUtil msru = new MailSendReceiverUtil();
msru.sendMail(mailInfo);
这样,我们就简单的将一个邮件发送的工具完成了,如果还需要写的完整的话,我们可以再添加更加规范的判断,例如在客户的输入邮箱地址时,利用正则表达式去判断邮箱的格式是否正确,利用同步锁去控制邮件发送,发送成功之后给用户界面相关提示等。
以上内容如有错误或不合理之处,还望大家指出。