最近项目中用到邮件功能,简单的参考网上的,自己修改,写了一下,代码如下:
package mail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
import javax.mail.internet.MimeUtility;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendMail {
private MimeMessage message;
private Session session;
private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private Properties properties = new Properties();
/*
* 初始化方法
*/
public SendMail(boolean debug) {
InputStream in = SendMail.class.getResourceAsStream("/reportMail.properties");
try {
properties.load(in);
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
} catch (IOException e) {
e.printStackTrace();
}
//需要经过授权
properties.put("mail.smtp.auth", true);
//linux上需要添加下面的配置(windows可不加)
properties.put("mail.smtp.localhost", "127.0.0.1");
//开启了 SSL 加密,qq邮箱特需的,其他的邮箱好像不用MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
session = Session.getInstance(properties);
//session.setDebug(debug);// 开启后有调试信息
message = new MimeMessage(session);
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
* @param attachment
* 附件
*/
public Boolean doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
Boolean flag=true;
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
//创建邮件的接收地址(数组)
String[] receivers = null;
if(receiveUser.contains(";")){
receivers=receiveUser.split(";");
}else{
receivers=new String[1];
receivers[0]=receiveUser;
}
// String[] to=receiveUser.split(";");
//后台也对邮箱做了格式校验,个人认为前台校验就可以了
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
int count =0;
for (int i = 0; i < receivers.length; i++)
{
if(receivers[i]!=""&&receivers[i]!=null){
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(receivers[i]);
if(matcher.matches()){
count=count+1;
}
}
}
InternetAddress[] sendTo = new InternetAddress[count];
for (int i = 0; i < receivers.length; i++)
{
if(receivers[i]!=""&&receivers[i]!=null){
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(receivers[i]);
if(matcher.matches()){
System.out.println("发送到:" + receivers[i]);
sendTo[i] = new InternetAddress(receivers[i]);
}
}
}
// message.setRecipient(Message.RecipientType.TO, sendTo);
message.setRecipients(Message.RecipientType.TO, sendTo);
// 收件人 单个人
// InternetAddress to = new InternetAddress(receiveUser);
// message.setRecipient(Message.RecipientType.TO, to);
// 邮件主题
message.setSubject(subject);
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart();
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart();
contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
attachmentBodyPart.setDataHandler(new DataHandler(source));
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
// 将multipart对象放到message中
message.setContent(multipart);
// 保存邮件
message.saveChanges();
transport = session.getTransport("smtp");
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost, sender_username, sender_password);
// 发送
transport.sendMessage(message, message.getAllRecipients());
System.out.println("send success!");
} catch (Exception e) {
e.printStackTrace();
flag=false;
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
flag=false;
}
}
}
return flag;
}
public static void main(String[] args) throws IOException {
SendMail se = new SendMail(true);
InputStream in = SendMail.class.getResourceAsStream("/reportMail.properties");
Properties properties = new Properties();
properties.load(in);
String receives = properties.getProperty("mail.receivers");
File sendFilePath = new File("D://Down//2016-04-22.zip");
se.doSendHtmlEmail("这时8月日报", "你好啊,happybao,这是8月的报表!", receives, sendFilePath);
}
}
以下是配置文件:
mail.smtp.host=smtp.qq.com
mail.sender.username=XXX@qq.com
mail.sender.password=XXX
mail.receivers=XXX@qq.com;XXX@163.com
好了,这样,邮件发送,就ok了!
需要注意的是:发件箱的密码,不是你登录QQ的密码,是你开始pop3服务的授权码: