简体   繁体   中英

How to send an asynchrone email with spring boot

I'm using spring boot 1.5. I'm trying to send async mail when user create an alert but it doesnt work and it doesn't display any error even when I'm debugging but in vain, so here's what I obtain. My question is how to test if my implementation of mail is correct or not, because I don't have any controller of it. Please help. Thank you for any suggestions

You can send asynchronous emails easily by using @Async annotation on your mail sending method. To enable Async support in your spring boot application use @EnableAsync like this:

@SpringBootApplication
@EnableAsync
public class SpringTestAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringTestAppApplication.class, args);
    }
}

Create a MailSender service and annotate mail sender method with @Async like this:

@Service
public class MailSenderService {

    @Async
    public void sendMail(....) {
       // your code
    }
}

Autowire the above service in your service and then call sendMessage method, example:

@Service
public class UserService {
    @Autowired
    private MailSenderService mailSenderService;

    User exampleMethod() {
        ..
        ..
        mailSenderService.sendMail(...);
    }
}

You can check this link for more information: https://www.baeldung.com/spring-async

UPDATE: If you want to use java mail api. Then you can take reference of below code:

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MailService {
    @Autowired
    EnvConfiguration envConfiguration;

    private static final Logger LOGGER = LoggerFactory.getLogger(MailService.class);

    @Async
    public void sendMail(String to, String subject, String htmlText, String fileName) {

        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtp.port", envConfiguration.getSMTPPort());
        props.put("mail.smtp.auth", envConfiguration.smtpAuthorized());
        props.put("mail.smtp.starttls.enable", envConfiguration.isStarTlsEnabled());
        props.put("mail.smtp.starttls.required", envConfiguration.isStarTlsRequired());

        Session session = Session.getDefaultInstance(props);
        Transport transport = null;
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(envConfiguration.getEmailFrom().replaceAll("\"", "")));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            msg.setSubject(subject);
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(htmlText, "text/html");
            transport = session.getTransport();
            transport.connect(envConfiguration.getEmailHost(), envConfiguration.getEmailUserName(),
                    envConfiguration.getEmailPassword());
            transport.sendMessage(msg, msg.getAllRecipients());
            LOGGER.info("Mail send successfully");
        } catch (MessagingException e) {
            LOGGER.error("Unable to send email trace" + e);
        } finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM