javaemailjakarta-mailmime-message

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


Currently, our application uses a javax.mail to send email, using javax.mail.MailMessage. We set the From headers of the email this way:

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

This works just fine, but we'd like to make the "From" section a little more user-friendly. Currently, someone receiving an email will see "mail@companyxyz.com" in the "From" section of their inbox. Instead, we'd like them to see "Company XYZ" there. I figure this is probably done with the addHeader() method, but I'm not sure what the header name would be.


Solution

  • 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