java - 如何在 Gmail SMTP 中指定显示名称?
问题描述
一个例子可以更好地解释我的问题:
如果“Mark Jones”拥有 xyz@gmail.com 并通过传统方法(Compose)向某人发送邮件,则收件人会收到一封标题为“Mark Jones”的邮件,后面跟着主题。但是通过 Gmail SMTP 发送的相同邮件的标题为“xyz”,后跟主题。
我正在为 SMTP 使用 javax.mail 库。即使我通过 Java SMTP 发送,我也希望显示“Mark Jones”而不是“xyz”。有没有办法实现这一点?
以下是我目前正在使用的代码:
System.setProperty("java.net.preferIPv4Stack" , "true");
Properties props = new Properties();
props.put("mail.smtps.user", "xyz@gmail.com");
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.port", "465");
props.put("mail.smtps.starttls.enable", "true");
props.put("mail.smtps.debug", "true");
props.put("mail.smtps.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz@gmail.com", "password");
}
});
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(this.subject);
msg.setFrom(new InternetAddress("xyz@gmail.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(this.to));
msg.setText(this.body);
try (Transport transport = session.getTransport("smtps")) {
transport.connect("smtp.gmail.com", Integer.valueOf("465"), "Mark Jones", "password");
transport.sendMessage(msg, msg.getAllRecipients());
}
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
解决方案
正如比尔香农建议的那样,下面的代码起到了作用
try{
msg.setFrom(new InternetAddress("xyz@gmail.com","Mark Jones"));
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
推荐阅读
- javascript - 为什么 0 < -0.75 < 1 为真?
- arrays - 在稳定的 Rust 中为大量数组实现特征的惯用方法是什么?
- angular - 量角器 - 从非角度页面切换到角度页面:“等待量角器与页面同步时出错”
- javascript - 为什么当“exact”未打开时,react-router 没有选择不完全匹配的路由?
- java - 使用 jersey 2 客户端上传文件:从 FormDataParam 的输入流转换为文件
- r - 我正在尝试在 R 中创建一个函数,用户必须猜测 1 到 100 之间的数字,直到它正确,但最多 7 次
- ember.js - 将 WSGI 配置为为单个页面应用程序提供单个 index.html 文件
- couchbase - Couchbase 按不在索引中的字段过滤
- python - 如何绘制实时图表
- sql - T SQL 导出到 XML