使用Spring 的封装的MailSender,确实省事多了!
但在使用中,还是得注意些问题
1.增加验证,否则会报:553 authentication is required 的错误信息
Properties prop = new Properties();
prop.setProperty("mail.smtp.auth", "true");
JavaMailSenderImpl.setJavaMailProperties(prop);
2.当邮件内容是HTML语言时的中文问题:
初始化MimeMessageHelper辅助类时,设置"GBK" encoding!
如:
MimeMessageHelper messageHelp = new MimeMessageHelper(message,true,"GBK");
同时在设置:<META http-equiv=Content-Type content='text/html; charset=GBK'>
如果都设置为"UTF-8",在某些邮件客户端标题是冷僻字时,不能正常显示!
3.邮件附件的中文问题!
spring的文档里面说MimeMessageHelper设置了encoding,同时对title,text,attach产生作用,但还是会出问题:
解决方法:MimeUtility.encodeWord(file.getName());就OK了!
以下是可以运行的代码
SendMailDemo.java
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SendMailDemo {
public void send163ByMutil() throws MessagingException {
JavaMailSenderImpl javaMail = new JavaMailSenderImpl();
javaMail.setHost("smtp.163.com");
javaMail.setPassword("passowrd");
javaMail.setUsername("username");
Properties prop = new Properties();
prop.setProperty("mail.smtp.auth", "true");
javaMail.setJavaMailProperties(prop);
MimeMessage message = javaMail.createMimeMessage();
MimeMessageHelper messageHelp = new MimeMessageHelper(message,true,"GBK");
messageHelp.setFrom("[email protected]");
messageHelp.setTo("[email protected]");
messageHelp.setSubject("邮件测试");
// messageHelp
String body = "<html><head><META http-equiv=Content-Type content='text/html; charset=GBK'></HEAD><title>test</title></head><body>dear 小燕子 \n ";
body+="<red>This is Text!</red> pic <img src='cid:a'></img><br>hello<img src='cid:b'></img></body></html>";
messageHelp.setText(body, true);
messageHelp.addInline("a", new File("E:/xiezi.jpg"));
messageHelp.addInline("b", new File("E:/logo.png"));
File file=new File("E:/Favorites中文文件.rar");
try {
messageHelp.addAttachment(MimeUtility.encodeWord(file.getName()), file);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
javaMail.send(message);
}
public static void main(String[] args) throws MessagingException {
SendMail send=new SendMail();
send.send163ByMutil();
}
}