javaMail发送邮件设置发件人中文昵称

时间:2021-12-22 18:09:19
public class TextMessage {
//发送信件邮箱的用户名及密码
static String username="272138576";
static String password="********";
public static void main(String [] args)throws Exception{
String from="272138576@qq.com";
String to="zousy999@qq.com";
String subject="test";
String body="test!!!";
Properties props = System.getProperties();
// 创建信件服务器
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");
// 得到默认的对话对象
Authenticator a = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
};
//创建Session实例
Session session = Session.getDefaultInstance(props, a);
//创建MimeMessage实例对象
MimeMessage msg=new MimeMessage(session);
//设置发信人
//msg.setFrom(new InternetAddress(from));
//设置自定义发件人昵称
String nick="";
try {
nick=javax.mail.internet.MimeUtility.encodeText("我的昵称");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
msg.setFrom(new InternetAddress(nick+" <"+from+">"));
//设置收信人
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
//设置发送日期
msg.setSentDate(new Date());
//设置邮件主题
msg.setSubject(subject);
//设置邮件正文
msg.setText(body);
Transport.send(msg);
}
}