Java可以实现发送邮件,依赖javax.mail包,最近在写用Java mail发送带附件的html格式邮件,工具类源码:
public class ReportSendHelper {
/**
* SMTP 服务器域名
*/
private String host;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String password;
/**
* 发送人邮箱
*/
private String from;
/**
* 收件人邮箱
*/
private String to;
/**
* 邮件主题
*/
private String subject;
/**
* html 格式正文的内容
*/
private String htmlContent;
/**
* 附件
*/
private String attachedFileName;
public ReportSendHelper(String host, String userName, String password, String from) throws MessagingException {
this.host = host;
this.userName = userName;
this.password = password;
this.from = from;
}
public void send() throws Exception {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
final String userName1 = userName;
final String password1 = password;
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName1, password1);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
Multipart multipart = new MimeMultipart();
if (htmlContent != null) {
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html");
multipart.addBodyPart(htmlPart);
}
if (attachedFileName != null) {
BodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachedFileName);
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName(attachedFileName);
multipart.addBodyPart(attachmentPart);
}
message.setContent(multipart);
Transport.send(message);
}
public void setTo(String to) {
this.to = to;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public void setAttachedFileName(String attachedFileName) {
this.attachedFileName = attachedFileName;
}
使用send方法发送邮件,邮件标题的中文可以正常显示,但邮件正文和附件名称中的中文以乱码显示,造成乱码的原因是编码问题,解决方法是:
为正文设置编码
htmlPart.setContent(htmlContent, "text/html;charset=gb2312");
使用javax.mail.internet.MimeUtility.encodeText()方法解决附件名称乱码问题
attachmentPart.setFileName(MimeUtility.encodeText(attachedFileName));