Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sender's address displayed rather than his name while sending with SimpleMailMessage in java

Tags:

java

email

spring

I send mail using SimpleMailMessage from org.springframework.mail package.But on the receiver side shows sender's address.I want to set his name.What method will use for this?Is there any method that available in SimpleMailMessage Class?I am using spring with hibernate.

code

 public void sendmail(){
 String emailSubject = "Test Message";                                          
 String emailBody = "For testing";
 SimpleMailMessage simpleMailMessage = new SimpleMailMessage();     
 simpleMailMessage.setTo("[email protected]");
 simpleMailMessage.setCc("[email protected]");
 simpleMailMessage.setSubject(emailSubject);
 simpleMailMessage.setText(emailBody);
 mailSender.send(simpleMailMessage);
 }
like image 848
Gayathri Rajan Avatar asked Feb 08 '23 21:02

Gayathri Rajan


1 Answers

Use Spring's MimeMessageHelper to set sender name and address.

        MimeMessagePreparator mailMessage = mimeMessage -> {
            MimeMessageHelper message = new MimeMessageHelper(
                    mimeMessage, true, "UTF-8");

            message.setFrom(senderEmail, senderName);
            [...]
        };
        mailSender.send(mailMessage);

See also my code snippet in this answer.

like image 91
Lars Behnke Avatar answered Feb 11 '23 11:02

Lars Behnke