springMai的html文本和附件的传递、解决html中文乱码、解决附件的中文名字乱码
package cn.itcast.mail;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import com.sun.xml.messaging.saaj.packaging.mime.internet.MimeUtility;
public class JavaSpringMailTest {
/*
* 解决html的中文乱码和附件的英文名字乱码
* 在使用中有一些中文的乱码问题需要解决!
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了!
*
*/
public static void sendMail() throws MessagingException, UnsupportedEncodingException
{
JavaMailSenderImpl impl = new JavaMailSenderImpl();
impl.setHost("smtp.163.com");
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
impl.setJavaMailProperties(properties);
impl.setUsername("ch469299503");
impl.setPassword("CH13410084766");
MimeMessage message = impl.createMimeMessage();
//第三个参数是解决乱码
MimeMessageHelper helper = new MimeMessageHelper(message, true,"GBK");
helper.setSubject("这是发送带有html文本");
helper.setFrom(new InternetAddress("ch469299503@163.com"));
helper.setTo(new InternetAddress("ch900915caohuan@163.com"));
//这是发送html文本,第二个参数表示前面的内容是html格式的,这里的cid:file,前面的cid表示contentId是一个固定的值,后面的file是一个
//占位符,后面的helper.addInline("file", classPathResource)就是来填充占位符的
/*
*
*
*/
//这里的head部分是为了解决乱码
helper.setText("<html><head><meta http-equiv='keywords' content='keyword1,keyword2,keyword3'>" +
"<meta http-equiv='description' content='this is my page'><meta http-equiv='content-type' content='text/html; charset=GBK'>" +
"</head><body>这就是爱<img src=cid:file></body></html>", true);
ClassPathResource classPathResource = new ClassPathResource("mianshi.jpg");
//这句代码在填充上面的占位符的同时,还将这张图片作为附件传过去
helper.addInline("file", classPathResource);
//解决附件的中文名字乱码问题,这是传递附件
helper.addAttachment(MimeUtility.encodeWord("面试.jpg"), classPathResource);
// impl.send(message);
}
public static void main(String[] args) {
try {
try {
sendMail();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
作者:ch469299503
补充:软件开发 , Java ,