-
Add the Java mail dependency in your pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
-
Optional but important add the dotenv dependency in your pom.xml
<dependency> <groupId>io.github.cdimascio</groupId> <artifactId>dotenv-java</artifactId> <version>2.3.1</version> </dependency>
-
Optional but important create a .env file in the project root folder and add the details below in it. Once done, open .gitignore file and add .env (i.e. write .env)
EMAIL_ADDRESS=yourgmail@gmail.com PASSWORD=your-password
-
Create a Bean of JavaMailSender (if you choose this option skip no. 5. This is the option i will use) or do add it in your application.properties file (5)
@Bean public JavaMailSender getJavaMailSender() { Dotenv dotenv = Dotenv.load(); String email = dotenv.get("EMAIL_ADDRESS"); //you can add your email here if you did not set up .env file String password = dotenv.get("PASSWORD"); //you can add your password here if you did not set up .env file JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.gmail.com"); mailSender.setPort(587); mailSender.setUsername(email); 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"); return mailSender; }
-
Application.properties file if you do not want to create a Bean of JavaMailerSender
spring.mail.host=smtp.gmail.com spring.mail.port=587 spring.mail.username=yourgmail@gmail.com spring.mail.password=yourpassword@gmail.com spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
-
The last step is to send email:
SimpleMailMessage message = new SimpleMailMessage(); message.setTo("toemail@email.com"); message.setSentDate(new Date()); message.setSubject("Your subject"); message.setText("Your message body"); try { javaMailSender.send(message); } catch (Exception e) { System.out.println("ERROR: " + e.getMessage()); }
-
If you experience this error:
https://support.google.com/mail/?p=BadCredentials
-
This is because Google allows you to generate specific credentials for apps. This is superior to using 'your own' account credentials. This means you will need to enable a two factor verification and create app specific password.
-
Follow this guide How to Create App-Specific Passwords in Gmail
-
Notifications
You must be signed in to change notification settings - Fork 0
ikechiU/JavaMailer
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
About
Guide to Spring Email with Gmail
Resources
Stars
Watchers
Forks
Releases
No releases published
Packages 0
No packages published