Home > front end >  Need to show a specific name instead of username as display name to mail send via Spring boot smtp?
Need to show a specific name instead of username as display name to mail send via Spring boot smtp?

Time:01-03

 SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo(recipients);
        message.setSubject("SERVICE DOWN");
        message.setText(".............");
        mailSender.send(message);

When using this, username is showing as display name. I want custom name like "SUPPORT"?

CodePudding user response:

As you can read on the API docs from Spring, you should use a different class: "Consider JavaMailSender and JavaMail MimeMessages for creating more sophisticated messages, for example messages with attachments, special character encodings, or personal names that accompany mail addresses."

CodePudding user response:

SimpleMailMessage does not support that function. You have to use another class that does. A good alternative would be MimeMessageHelper. It is pretty straightforward to use and supports more functionalities.

Here is a simple example

First of all, a MailSender object is required. You could create one or create a bean out of it:

JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(587);

mailSender.setUsername("[email protected]");
mailSender.setPassword("password");

Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");

Then send the message:

MimeMessagePreparator mailMessage = mimeMessage -> {

    MimeMessageHelper message = new MimeMessageHelper(
            mimeMessage, true, StandardCharsets.UTF_8);
    try {
        message.setFrom(senderEmail, senderName); // Here comes your name
        
        message.addTo(recipientEmail);  

        
        message.setReplyTo(senderEmail);
        message.setSubject(subject);
        message.setText(fallbackTextContent, htmlContent);
        
    } catch (Exception e) {
        throw new MailDeliveryServiceException(recipientEmail, e);
    }
};

mailSender.send(mailMessage);
  • Related