Send an email using JavaMail on AWS

Try using Java Mail on AWS

This time, I will try sending Java mail via google's SMTP using AWS EC2 launched in the previous article

Run Java on EC2

Check if Java is included in EC2 Ssh to EC2 launched last time ssh -i [pem file] [email protected]

Make sure Java is not included java -version -bash: java: command not found javac -version -bash: javac: command not found yum list installed | grep java ** Nothing is displayed

Drop openJDK with yum sudo yum update sudo yum -y install java-1.8.0-openjdk-devel

reconfirmation You can see that Java is installed java -version openjdk version "1.8.0_222" OpenJDK Runtime Environment (build 1.8.0_222-b10) OpenJDK 64-Bit Server VM (build 25.222-b10, mixed mode)

javac -version javac 1.8.0_222

Let's write a program to display Hello World as a trial

public class HelloWorld {

  public static void main(String[] args) {
    System.out.println("HelloWorld");
  }

}

javac HelloWorld.java ls HelloWorld.class HelloWorld.java

Display confirmation java HelloWorld ————————— HelloWorld —————————

Create a program for sending emails in the local environment

Write the code for sending emails in Java Development environment uses Eclipse and standard OpenJDK 1.8 ~ JavaMail requires a dedicated library, so I will drop it Drop it from the following area and use it https://www.oracle.com/technetwork/java/index-138643.html

Class design calls mail builder from mail client and gives setting value Send processing with sendMail method The mail builder class has an inner / outer configuration Build a builder in the inner class and a MailSend class in the outer class

Email client

import mail_builder.SendMail;

public class JavaMailClients {

  public static void main(String[] args) {

    SendMail.MailBuilder mailBuilder = new SendMail.MailBuilder();

    mailBuilder.setTo("Email destination address");
    mailBuilder.setFrom("Email sender address");
    mailBuilder.setPassword("google email password");
    mailBuilder.setUserName("google mail username");
    mailBuilder.setSmtpHost("smtp.gmail.com"); //Use google smtp server
    mailBuilder.setSmtpPort("587");


    String subject = "Test email";
    String contents = "Test transmission";
    mailBuilder.build().sendMail(subject, contents);

  }

}

Email sender

package mail_builder;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Address;
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;

public class SendMail {

  // mail contents
  private String to = "";               // send target
  private String from = "";             // mail from

  // mail user settings
  private String userName = "";         // mail account(example google account)
  private String password = "";         // mail account password
  private String smtpHost = "";
  private String smtpPort = "";
  private final String smtpAuth = "true";
  private final String starttls = "true";
  private final String connectionTimeoutValue = "10000";
  private final String timeoutValue = "10000";

  // others
  private final String charSet = "ISO-2022-JP";
  private final String encoding = "base64";


  // smtp settings
  private Properties mailProperties = new Properties();
  private final String SMTP_HOST = "mail.smtp.host";
  private final String SMTP_PORT = "mail.smtp.port";
  private final String SMTP_AUTH = "mail.smtp.auth";
  private final String SMTP_START_TLS = "mail.smtp.starttls.enable";
  private final String SMTP_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
  private final String SMTP_TIMEOUT = "mail.smtp.timeout";


  public static class MailBuilder {

    private String to = "";
    private String from = "";
    private String userName = "";
    private String password = "";
    private String smtpHost = "";
    private String smtpPort = "";

    public MailBuilder setTo(String to) {
      this.to = to;
      return this;
    }

    public MailBuilder setFrom(String from) {
      this.from = from;
      return this;
    }

    public MailBuilder setUserName(String userName) {
      this.userName = userName;
      return this;
    }

    public MailBuilder setPassword(String password) {
      this.password = password;
      return this;
    }

    public MailBuilder setSmtpHost(String smtpHost) {
      this.smtpHost = smtpHost;
      return this;
    }

    public MailBuilder setSmtpPort(String smtpPort) {
      this.smtpPort = smtpPort;
      return this;
    }

    public SendMail build() {
      return new SendMail(this);
    }

  }



  private SendMail(MailBuilder mailBuilder) {
    this.to = mailBuilder.to;
    this.from = mailBuilder.from;
    this.userName = mailBuilder.userName;
    this.password = mailBuilder.password;
    this.smtpHost = mailBuilder.smtpHost;
    this.smtpPort = mailBuilder.smtpPort;
  }



  public void sendMail(String subject, String contents) {

    mailProperties.setProperty(SMTP_HOST, smtpHost);
    mailProperties.setProperty(SMTP_PORT, smtpPort);
    mailProperties.setProperty(SMTP_AUTH, smtpAuth);
    mailProperties.setProperty(SMTP_START_TLS, starttls);
    mailProperties.setProperty(SMTP_CONNECTION_TIMEOUT, connectionTimeoutValue);
    mailProperties.setProperty(SMTP_TIMEOUT, timeoutValue);

    Session session = Session.getInstance(mailProperties,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
         }
      }
    );

    try {
      MimeMessage message = new MimeMessage(session);

      message.setFrom(new InternetAddress(from, "test_user"));
      message.setReplyTo(new Address[]{ new InternetAddress(from) });
      message.setRecipient( Message.RecipientType.TO, new InternetAddress(to) );
      message.setSubject(subject, charSet);
      message.setText(contents, charSet);
      message.setHeader("Content-Transfer-Encoding", encoding);

      Transport.send(message);

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException(e);
    }

  }


}

I sent it to my mobile phone, but an Exception occurred It seems that you need to allow mail server access from others with your google account Turn it on on the screen below スクリーンショット 2019-11-03 1.54.15.png

Re-execution result

[From :]
 test_user
[Subject :]
*I can't see it for some reason
[Content:]
$B%F%9%HAw?.(B

Garbled characters are occurring $B%F%9%HAw?.(B

Try changing the hard-coded character code settings. x-windows-iso2022jp (I used this, but it has already been changed in the code described ↓ ISO-2022-JP

result

[From :]
 test_user
[Subject :]
Test email
[Content:]
Test transmission

Result confirmation completed Sweep data in Eclipse Send to server in archive format スクリーンショット 2019-11-03 2.02.11.png スクリーンショット 2019-11-03 2.03.00.png

Run on EC2

To EC2 server [local]

scp -i [pem file] SendMail.zip [email protected]:~;
ssh -i [pem file] [email protected]

[ec2]

unzip SendMail.zip 
ls
bin  src
cd bin
ls
JavaMailClients.class  javax.mail-1.6.2.jar  mail_builder

java JavaMailClients
Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/MessagingException
	at mail_builder.SendMail$MailBuilder.build(SendMail.java:86)

It was successful locally, but for some reason an error

In the local environment, I ran it in Eclipse, but decided to run it on MacOS Install Java 8 with HomeBrew [local terminal]

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew cask install adoptopenjdk8
Error: Cask 'adoptopenjdk8' is unavailable: No Cask with this name exists.

I get an error even with Brew Apparently there is no java8 in the repository

Even if I try to drop it officially, it will be annoying because registration is required after changing to oracle I searched for openjdk for MacOS but couldn't find it ...

I was sticky for about 2 hours, but I got hooked

Looking at the contents of the Exception, because the javax mail class cannot be read Googling about classpath settings If you include a jar file, you know that you need to set the jar in the classpath

Re-execute java -cp .:./javax.mail-1.6.2.jar JavaMailClients

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 534-〜〜〜〜

Another error ... It seems that the access authentication to the mail server has failed. When I googled about it, the setting method was written on the following site https://stackoverflow.com/questions/34433459/gmail-returns-534-5-7-14-please-log-in-via-your-web-browser/34433953

Set again and execute java -cp .:./javax.mail-1.6.2.jar JavaMailClients

It worked safely. Since it is never executed using the java command I got hooked there, but I managed to do it.

that's all

Recommended Posts

Send an email using JavaMail on AWS
[2020 version] How to send an email using Android Studio Javamail
[Java] Send an email using Amazon SES
Send an email with a PDF attachment via JavaMail
[Spring Boot] Send an email
Send an email from gmail with Ruby
Build an environment with Docker on AWS
How to send push notifications on AWS
I want to send an email in Java.
Send email using Amazon SES SMTP in Java
Procedure for publishing an application using AWS (5) Publish an application
Send emails using Docker container on Raspberry Pi 3
Build a Laravel environment on an AWS instance
How to install Ruby on an EC2 instance on AWS
I built an Ubuntu environment on Windows 10 using WSL2.
Deploy laravel using docker on EC2 on AWS ① (Create EC2 instance)
[Docker] Build an Apache container on EC2 using dockerfile
Using JDBC on Linux
Creating a docker host on AWS using Docker Machine (personal memorandum)
[Amateur remarks] Build multiple WordPress on AWS using Docker Compose
Deploy laravel using docker on EC2 on AWS ② (Elastic IP acquisition-linking)
Ruby on Rails Email automatic sending function setting (using gmail)
How to create an application server on an EC2 instance on AWS
Launch an application on Code Engine using IBM Cloud Shell
Deploy laravel using docker on EC2 on AWS ④ (git clone ~ deploy, migration)
Procedure for publishing an application using AWS (4) Creating a database
I want to manually send an authorization email with Devise