Thursday 27 October 2022

Email Sending Configuration


Email Configuration


Step 1 : Need Spring Email Dependency 
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Step 2 : Required Email properties 
Properties props = new Properties ();
props.put ("mail.smtp.auth", Boolean.TRUE);
props.put ("mail.smtp.starttls.enable", Boolean.TRUE);
props.put ("mail.smtp.host", "smtp-mail.outlook.com"); // gmail : smtp-mail.gmail.com
props.put ("mail.smtp.port", "587");

Step 3 : Use below code to send email using springboot application 
try
{
Session session = Session.getInstance(
props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("user-email", "user-password");
}
})
;
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("user-email", false));

msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse("user-mails"));

msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("user-email"));
msg.setSubject("Email Configuration");
msg.setSentDate(new Date());

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("MESSAGE_BODY",
MediaType.TEXT_HTML_VALUE);

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

MimeBodyPart attachPart = new MimeBodyPart();
attachPart.attachFile(file);
multipart.addBodyPart(attachPart);
msg.setContent(multipart);
Transport.send(msg);
}
catch (Exception exe)
{
log.error ("error @ Email sending {} ", exe);
}

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...