5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GCEでSendGrid使う~Spring mail(Java Mail)編~

Last updated at Posted at 2016-04-14

はじめに

GCE上でSendGridを使います。Spring Bootでアプリケーションを開発している人ならSpring Mail(Java Mail)がオススメ。事前にSendGridのアカウントを作っておいて下さい。GCEも使えるようにしておいてください。

依存ファイル

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
  <version>1.3.2.RELEASE</version>
</dependency>

<dependency>
  <groupId>com.sun.mail</groupId>
  <artifactId>javax.mail</artifactId>
  <version>1.5.5</version>
</dependency>

前提はSpring Bootのアプリケーションを既に作っていることです。なので、Spring Boot系の依存ファイルは省略します。

メール送信部分

@Autowired
private JavaMailSender javaMailSender;

public void setMailSender(JavaMailSender javaMailSender) {
  this.javaMailSender = javaMailSender;
}

public void send() {
  try {
    MimeMessage mail = javaMailSender.createMimeMessage();
    mail.setHeader("Content-Transfer-Encoding", "base64");
    MimeMessageHelper helper = new MimeMessageHelper(mail, false);
    helper.setTo("To");
    helper.setReplyTo("FROM");
    helper.setFrom("FROM");
    helper.setSubject("SUBJECT");
    helper.setText("CONTENT");
    javaMailSender.send(mail);
  } catch (MessagingException e) {
    //Exception
  }
}

SendGridの設定

application.properties
spring.mail.default-encoding=UTF-8
spring.mail.protocol=smtp
spring.mail.host=smtp.sendgrid.net
spring.mail.port=2525
spring.mail.jndi-name=mail/Session
spring.mail.username=your.sendgrid.username
spring.mail.password=your.sendgrid.password
spring.mail.properties.mail.smtp.auth=true

spring.mail.usernameにSendGridのユーザー名を、spring.mail.passwordにSendGridのパスワードをそれぞれ入力します。

終わりに

以上でGCEからSendGrid経由でメールの送信ができます。既にSpring Mailを使っていた人は気づいたと思いますが、基本的にはSpring Mail用の設定ファイルを多少変更するだけです。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?