48

目前,我们的应用程序使用 javax.mail 发送电子邮件,使用 javax.mail.MailMessage。我们以这种方式设置电子邮件的 From 标头:

Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("mail@companyxyz.com"));

这工作得很好,但我们想让“发件人”部分更加用户友好。目前,收到电子邮件的人会在收件箱的“发件人”部分看到“mail@companyxyz.com”。相反,我们希望他们在那里看到“公司 XYZ”。我认为这可能是通过 addHeader() 方法完成的,但我不确定标题名称是什么。

4

4 回答 4

118

好的,阅读有关所有相关类的文档会很有帮助。正确的语法应该是

Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("mail@companyxyz.com", "Company XYZ"));

来源:https ://javamail.java.net/nonav/docs/api/javax/mail/internet/InternetAddress.html

于 2009-10-14T16:40:16.280 回答
22

如果您想将电子邮件 + 姓名存储在一个字符串中(比保留两个字符串更容易):

Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("Company XYZ <mail@companyxyz.com>"));
于 2013-04-15T12:56:04.570 回答
3

如果我使用带有特殊字符(如 \u00FA)的本地化文本,我会遇到一些 pop3 客户端的电子邮件地址别名编码问题,如果我只使用

MimeMessage m = new MimeMessage(session);
m.setFrom();

它可以通过单独的电子邮件地址和别名通过调用来解决:

MimeMessage m = new MimeMessage(session);
            m.setFrom(new InternetAddress(session.getProperty("mail.from"), session.getProperty("mail.from.alias"),"UTF8"));

参考:https://javamail.java.net/nonav/docs/api/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String,%20java.lang.String,%20java.lang.String)

于 2014-03-28T12:26:50.830 回答
2
ic = new InitialContext();

final Session session = (Session) ic.lookupLink(snName);
final Properties props = session.getProperties();

props.put("mail.from", mailFrom); //blabla@mail.com
props.put("mail.from.alias", mailName);//"joao Ninguem"

// Create a message with the specified information.
final MimeMessage msg = new MimeMessage(session);
msg.setSubject(subject);
msg.setSentDate(new Date());

msg.setFrom(new InternetAddress(session.getProperty("mail.from"), session.getProperty("mail.from.alias"), "UTF8"));


msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo, false));
msg.setContent(body, "text/html");

// Create a transport.
Transport.send(msg);
于 2018-03-20T17:19:11.500 回答