I sent an email in Java

Introduction

Since I was involved in MA tools, I researched email delivery. I made a simple mail delivery (html mail) program using google's smtp server.

Language / What to use

・ Java -Mail.jar: download link -Activation.jar: download link ・ Google smtp server

Process flow

As a rough processing flow

smtp authentication → Delivery content, destination, sender settings → Send

It's a simple or normal flow.

coding

import

import process


import javax.mail.Address;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.io.UnsupportedEncodingException;
import java.util.Date;

First of all, you need to import them as a premise.

smtp authentication

python


Properties props = new Properties();
//SMTP server settings. Set google's SMTP server here
props.setProperty("mail.smtp.host","smtp.gmail.com"); 
//Change port number for SSL
props.setProperty("mail.smtp.port", "465");
//Time-out setting
props.setProperty("mail.smtp.connectiontimeout", "60000");
props.setProperty("mail.smtp.timeout", "60000");

//Authentication
props.setProperty("mail.smtp.auth", "true");
//This setting is required when using SSL
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port","465");

//Create session using the information set in props
final Session session = Session.getInstance(props, new Authenticator() {
	protected PasswordAuthentication getPasswordAuthentication() {
        //Set your gmail account and password here
		return new PasswordAuthentication("[email protected]","your password");
	}
});

In this way, set the credentials in Properties and create a session Assign authentication information to Session type variable, session.

Delivery content, destination, source settings

python


//Set the variable session
MimeMessage contentMessage = new MimeMessage(session);
//Email content information
String mailContents = "<html><body><h1>hello</h1></body></html>"
try {
    //Set the source address, display name, and character code
	Address addFrom = new InternetAddress("[email protected]", "Mr. A", "UTF-8");
	contentMessage.setFrom(addFrom);
    //Set the destination address, display name, and character code
	Address addTo = new InternetAddress("[email protected]","Mr. B","UTF-8");
	contentMessage.addRecipient(Message.RecipientType.TO, addTo);
    //Set subject
	contentMessage.setSubject("Hello! !!","UTF-8");
    //You have specified the content type of the email. In this case it will be an HTML email
	contentMessage.setHeader("Content-Type", "text/html; charset=UTF-8");
    //Setting the content of the email
	contentMessage.setContent(mailContents, "text/html; charset=UTF-8");
    //Setting of date etc.
	contentMessage.setSentDate(new Date());
} catch (MessagingException e) {
	e.printStackTrace();
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}

Set the delivery content, destination, and source Assign it to a variable called contentMessage of type MimeMessage. By the way, if you set the content type to text, you can deliver text mail.

Send

python


//send e-mail
try {
    //Set the contentMessage earlier
	Transport.send(contentMessage);
} catch (AuthenticationFailedException e) {	
    //Authentication failure
	e.printStackTrace();
} catch (MessagingException e) {
	//Connection failure to smtp server
	e.printStackTrace();
}

This will send the email.

Summary

It seems that the basic mail delivery in Java is basically like this. To make this even faster, use threads, insert characters into the content, etc. It's interesting because you can do various things. The actual code can be found on github below, if you like.

Source: github

Recommended Posts

I sent an email in Java
I want to send an email in Java.
I made an annotation in Java.
I made roulette in Java.
Implement Email Sending in Java
I tried metaprogramming in Java
I wrote about Java downcast in an easy-to-understand manner
I tried using an extended for statement in Java
I created a PDF in Java.
Try an If expression in Java
I wrote Goldbach's theorem in java
I tried using JWT in Java
Run an external process in Java
[Java] I participated in ABC-188 of Atcorder.
I tried using Elasticsearch API in Java
Map without using an array in java
I tried the new era in Java
[Java] Send an email using Amazon SES
I did OpenCV camera calibration in Java
[* Java *] I participated in JJUG CCC 2019 Spring
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
I want to ForEach an array with a Lambda expression in Java
Pi in Java
FizzBuzz in Java
I made a primality test program in Java
Send email using Amazon SES SMTP in Java
Second decoction: Try an If expression in Java
I tried to implement deep learning in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I wrote a primality test program in Java
I made a rock-paper-scissors game in Java (CLI)
rsync4j --I want to touch rsync in Java.
What I learned in Java (Part 2) What are variables?
I tried to output multiplication table in Java
How to solve an Expression Problem in Java
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
I wrote a prime factorization program in Java
Interpreter implementation in Java
Make Blackjack in Java
I made a simple calculation problem game in Java
I tried Mastodon's Toot and Streaming API in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
Write ABNF in Java and pass the email address
I want to do something like "cls" in Java
NVL-ish guy in Java
Combine arrays in Java
I first touched Java ②
"Hello World" in Java
Callable Interface in Java
I tried to implement Firebase push notification in Java
I tried using Google Cloud Vision API in Java
I first touched Java ③
[java] throw an exception
Comments in Java source
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
Azure functions in java