I am trying to send a message using spring boot. I have 3 files as follows
MailSender.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
public class MailSender
{
@Autowired
private static JavaMailSender mailSender;
public static void main(String[] args)
{
sendemail();
}
public static void sendemail() {
MimeMessage mail = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
helper.setTo("emailsendertester24@gmail.com");
helper.setFrom("emailsendertester24@gmail.com");
helper.setSubject("Lorem ipsum");
helper.setText("Lorem ipsum dolor sit amet [...]");
} catch (MessagingException e) {
e.printStackTrace();
} finally {}
mailSender.send(mail);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Example</groupId>
<artifactId>SendingEmail</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
</dependencies>
</project>
and application.properties
spring.mail.host=smtp.gmail.com
spring.mail.username=*****
spring.mail.password=*****
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.socketFactory.port = 25
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable=true
So, now when I try to run my MailSender class, it gives me the error "Exception in thread" main "java.lang.NullPointerException" in the line MimeMessage mail = mailSender.createMimeMessage (); I found out that the properties of mailSender are null since it cannot get properties from application.properties file.
source
share