Setting the from name in a javax.mail.MimeMessage?

流过昼夜 提交于 2019-11-28 06:43:23
abeger

OK, reading documentation about ALL the classes involved would have been helpful. The correct syntax should be

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

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

If you want to store the email + the name in one string (easier than keeping two string):

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

In case when I used localized text with special characters like \u00FA I had problems with encoding email address alias for some pop3 clients if I'd used just

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

It can be resolved by separate email address and alias by invoke:

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

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

Rodrigo Turassa
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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!