服务启动初始化
在启动时直接初始化,进行编码设置
private void init() {
// 默认java关于邮箱的参数splitlongparameters为true, 即太长会处理为.bin
// 我们手动关闭即可
System.setProperty("mail.mime.splitlongparameters", "false");
}
邮件发送设置编码格式
在进行获取email对象的时候,配置参数设置
//设置编码格式为UTF-8
properties.setProperty("mail.mime.charset", "UTF-8");
public Session initMail() {
try {
//创建一个配置文件并保存
Properties properties = new Properties();
properties.setProperty("mail.host", "smtp.qq.com");
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.mime.charset", "UTF-8");
//QQ存在一个特性设置SSL加密
MailSSLSocketFactory sf = null;
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(qqUserName, qqPassWord);
}
});
// //开启debug模式
session.setDebug(true);
return session;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}