我无法设置自定义显示名称。日志看起来正确:
发件人:管理员显示名称 [电子邮件受保护] 收件人:[电子邮件受保护]
但在电子邮件结果中,显示名称丢失。
我认为我使用了正确的 InternetAddress 构造函数,但它不起作用。它只是显示电子邮件地址。 我在 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 = "[email protected]";
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 = "[email protected]";
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();
}
}
这是如下所示的解决方案
您尝试将
setSender
与包含 setFrom
的
InternetAddress
对象一起使用,而不是使用
display name
更换:
mimeMessage.setSender(addressFrom);
与:
mimeMessage.setFrom(addressFrom);