I'm not able to set a custom display name. Logs seem correct:
Sender: Admin Display Name admin.emailaddress@gmail.com To: user.mailaddress@gmail.com
But in the email resulted, display name is missing.
I think I used the correct InternetAddress constructor, but it doesn't work. It simply display the email address. I run on JDK 17 & Spring Boot 3.1.10
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.stereotype.Service;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import java.util.Properties;
public class EmailService {
private final static String from = "admin.emailaddress@gmail.com";
private final static String displayNameFrom = "Admin Display Name";
private final static String password = "gmail-api-password";
//@Async("asyncExecutor")
public void send(){
Properties props = loadProperties();
String subject = "Test subject";
String message = "Hello World";
String recipientAddress = "user.mailaddress@gmail.com";
try{
Session session = Session.getDefaultInstance(props,
new jakarta.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
session.setDebug(true);
Transport transport = session.getTransport();
//InternetAddress addressFrom = new InternetAddress(from);
InternetAddress addressFrom = new InternetAddress(from, displayNameFrom); //TODO test
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSender(addressFrom);
mimeMessage.setSubject(subject);
mimeMessage.setContent(message+ "\r\n", "text/plain");
if(email.getReplyTo() != null){
mimeMessage.setReplyTo(new Address[]{new InternetAddress(email.getReplyTo())});
}
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
transport.connect();
Transport.send(mimeMessage);
transport.close();
} catch(Exception e){
System.err.println(e);
//System.err.println("email : "+email.toString());
}
}
private Properties loadProperties(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
}
public class TestDisplayName(){
public static void main(String[] args){
EmailService emailService = new EmailService();
emailService.send();
}
}
Here is the solution shown below
Instead of using setSender
, you try to use setFrom
with the InternetAddress
object that includes the display name
Replace:
mimeMessage.setSender(addressFrom);
with:
mimeMessage.setFrom(addressFrom);