Send email with replyTo field using Spring Boot


For sending emails Java provides a library JavaMail API using which one can send emails or if you are using the Spring framework then you can use Springs email library. In Spring boot you can do this in a very simple way by including the spring boot mail starter library, application properties, and one function.

In some scenarios when you are sending an email via some system then you need to provide the sender’s different email to get an automatic reply. For this, you should use replyTo filed of Java email API.

Gradle Dependancy

implementation 'org.springframework.boot:spring-boot-starter-mail:2.7.2'

Now you need to provide the following properties in application properties or yaml file

spring.mail.host=smtp.gmail.com // smtp host
spring.mail.port=587 // Port
spring.mail.username=xxxxx.xxxx@gmail.com // Email or user name
spring.mail.password=$#%JNBVKJH //Password

Code to send email

@Data
@NoArgsConstructor
public class Mail 
{
	private String mailFrom;
    private String mailTo;
    private String mailCc;
    private String mailBcc;
    private String mailSubject;
    private String mailContent;
    private String contentType = "text/plain";
    private List <Object> attachments;
    
    public Date getMailSendDate() {
        return new Date();
    }
}
public void sendEmail(Mail mail) throws IOException {

		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
			mimeMessageHelper.setSubject(mail.getMailSubject());
			mimeMessageHelper.setFrom(new InternetAddress(mail.getMailFrom()));
			mimeMessageHelper.setTo(mail.getMailTo());
			mimeMessageHelper.setText(mail.getMailContent());
			mimeMessageHelper.setReplyTo(new InternetAddress("sendersemail@abc.com"));
			javaMailSender.send(mimeMessageHelper.getMimeMessage());
		} 
		catch (MessagingException e) {
			e.printStackTrace();
		}

	}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.