春 - Gmail経由で電子メールを送信MailSenderでSMTPサーバー

Spring – MailSenderを使用してGmail SMTPサーバー経由で電子メールを送信する

Springには、JavaMailAPIを介した電子メール送信プロセスを簡素化するための便利な「org.springframework.mail.javamail.JavaMailSenderImpl」クラスが付属しています。 これは、Springの「JavaMailSenderImpl」を使用してGmailSMTPサーバー経由でメールを送信するMavenビルドプロジェクトです。

1. プロジェクトの依存関係

JavaMailとSpringの依存関係を追加します。

ファイル:pom.xml


  4.0.0
  com.example.common
  SpringExample
  jar
  1.0-SNAPSHOT
  SpringExample
  http://maven.apache.org

  
    
        Java.Net
        http://download.java.net/maven/2/
    
  

  

    
              junit
              junit
              3.8.1
             test
    

    
    
        javax.mail
        mail
        1.4.3
    

    
    
            org.springframework
        spring
        2.5.6
    

  

2. 春のメール送信者

SpringのMailSenderインターフェースでメールを送信するJavaクラス。

ファイル:MailMail.java

package com.example.common;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class MailMail
{
    private MailSender mailSender;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String from, String to, String subject, String msg) {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(msg);
        mailSender.send(message);
    }
}

3. Bean構成ファイル

mailSender Beanを構成し、Gmail SMTPサーバーの電子メールの詳細を指定します。

ファイル:Spring-Mail.xml




    
    
    
    

    
       
              true
              true
           
    



    


4. それを実行します

package com.example.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App
{
    public static void main( String[] args )
    {
        ApplicationContext context =
             new ClassPathXmlApplicationContext("Spring-Mail.xml");

        MailMail mm = (MailMail) context.getBean("mailMail");
        mm.sendMail("[email protected]",
               "[email protected]",
               "Testing123",
               "Testing only \n\n Hello Spring Email Sender");

    }
}

ソースコードをダウンロード