private MimeMessage message;
private Session session;
告旅或 private Transport transport;
private String mailHost = "";
private String sender_username = "";
private String sender_password = "";
private static Properties properties = new Properties();
private String sendResult = "";
private static int total =0,filter=0;
static{
/*
* #----------------这两个是构建session必须的字段----------
#smtp服务器
mail.smtp.host=smtp.163.com
#身份验证
mail.smtp.auth=true
#--------------------------------------------------------------
#发送者的邮箱用户名
mail.sender.username=xxx@xx.com
#发送者的邮箱密码
mail.sender.password=xxxxxxxxxx*/
properties.put("mail.smtp.host", "smtp.163.com");
properties.put("mail.smtp.auth", "true");
properties.put("mail.sender.username", "abcdefghijk@163.com");
properties.put("mail.sender.password", "***************");
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
* @param attachment
* 附件
*/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
this.mailHost = properties.getProperty("mail.smtp.host");
this.sender_username = properties.getProperty("mail.sender.username");
this.sender_password = properties.getProperty("mail.sender.password");
session = Session.getInstance(properties);
session.setDebug(false);// 开启后有调试信息
message = new MimeMessage(session);
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username);
message.setFrom(from);
// 收件人袜伍
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就可以很方便的搞定
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
//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());
sendResult = "send success!";
System.out.println(sendResult);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}