web-dev-qa-db-ja.com

javaを使用してメールを送信します

Javaを使用してメールを送信しようとしています。

import Java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail {

   public static void main(String [] args) {

      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String Host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.Host", Host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("This is actual message");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

エラーが発生しています:

javax.mail.MessagingException: Could not connect to SMTP Host: localhost, port: 25;
  nested exception is:Java.net.ConnectException: Connection refused: connect
        at com.Sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.Java:1706)
        at com.Sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.Java:525)

このコードは電子メールを送信するために機能しますか?

107
Mohit Bansal

次のコードは、Google SMTPサーバーで非常にうまく機能します。 Googleのユーザー名とパスワードを入力する必要があります。

import com.Sun.mail.smtp.SMTPTransport;
import Java.security.Security;
import Java.util.Date;
import Java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String title, String message) throws AddressException, MessagingException {
        GoogleMail.Send(username, password, recipientEmail, "", title, message);
    }

    /**
     * Send email using GMail SMTP server.
     *
     * @param username GMail username
     * @param password GMail password
     * @param recipientEmail TO recipient
     * @param ccEmail CC recipient. Can be empty if there is no CC recipient
     * @param title title of the message
     * @param message message to be sent
     * @throws AddressException if the email address parse failed
     * @throws MessagingException if the connection is dead or not in the connected state or if the message is not a MimeMessage
     */
    public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        Security.addProvider(new com.Sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.Host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set 
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://Java.Sun.com/products/javamail/javadocs/com/Sun/mail/smtp/package-summary.html
                http://forum.Java.Sun.com/thread.jspa?threadID=5205249
                smtpsend.Java - demo program from javamail
        */
        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());      
        t.close();
    }
}

2015年12月11日に更新

ユーザー名+パスワードは推奨されるソリューションではなくなりました。これは、に起因するものです

これを試したところ、Gmailはこのコードでユーザー名として使用したメールに、Googleアカウントへのログイン試行を最近ブロックしたというメールを送信し、サポートページsupport.google.com/accounts/answer/6010255にリダイレクトしました動作するように探します。送信に使用されるメールアカウントは、独自のセキュリティを低下させる必要があります

GoogleはGmail APIをリリースしました- https://developers.google.com/gmail/api/?hl=en 。ユーザー名+パスワードの代わりに、oAuth2メソッドを使用する必要があります。

Gmail APIを使用するためのコードスニペットを次に示します。

GoogleMail.Java

import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.Message;
import Java.io.ByteArrayOutputStream;
import Java.io.IOException;
import Java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author doraemon
 */
public class GoogleMail {
    private GoogleMail() {
    }

    private static MimeMessage createEmail(String to, String cc, String from, String subject, String bodyText) throws MessagingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);
        InternetAddress tAddress = new InternetAddress(to);
        InternetAddress cAddress = cc.isEmpty() ? null : new InternetAddress(cc);
        InternetAddress fAddress = new InternetAddress(from);

        email.setFrom(fAddress);
        if (cAddress != null) {
            email.addRecipient(javax.mail.Message.RecipientType.CC, cAddress);
        }
        email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
        email.setSubject(subject);
        email.setText(bodyText);
        return email;
    }

    private static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
    }

    public static void Send(Gmail service, String recipientEmail, String ccEmail, String fromEmail, String title, String message) throws IOException, MessagingException {
        Message m = createMessageWithEmail(createEmail(recipientEmail, ccEmail, fromEmail, title, message));
        service.users().messages().send("me", m).execute();
    }
}

OAuth2を介して承認済みのGmailサービスを構築するためのコードスニペットを以下に示します。

Utils.Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.oauth2.Oauth2;
import com.google.api.services.oauth2.model.Userinfoplus;
import Java.io.BufferedWriter;
import Java.io.File;
import Java.io.FileOutputStream;
import Java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.OutputStreamWriter;
import Java.nio.file.Files;
import Java.nio.file.Paths;
import Java.security.GeneralSecurityException;
import Java.util.HashSet;
import Java.util.Set;
import org.Apache.commons.logging.Log;
import org.Apache.commons.logging.LogFactory;
import org.yccheok.jstock.engine.Pair;

/**
 *
 * @author yccheok
 */
public class Utils {
    /** Global instance of the JSON factory. */
    private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport httpTransport;

    private static final Log log = LogFactory.getLog(Utils.class);

    static {
        try {
            // initialize the transport
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        } catch (IOException ex) {
            log.error(null, ex);
        } catch (GeneralSecurityException ex) {
            log.error(null, ex);
        }
    }

    private static File getGmailDataDirectory() {
        return new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "authentication" + File.separator + "gmail");
    }

    /**
     * Send a request to the UserInfo API to retrieve the user's information.
     *
     * @param credentials OAuth 2.0 credentials to authorize the request.
     * @return User's information.
     * @throws Java.io.IOException
     */
    public static Userinfoplus getUserInfo(Credential credentials) throws IOException
    {
        Oauth2 userInfoService =
            new Oauth2.Builder(httpTransport, JSON_FACTORY, credentials).setApplicationName("JStock").build();
        Userinfoplus userInfo  = userInfoService.userinfo().get().execute();
        return userInfo;
    }

    public static String loadEmail(File dataStoreDirectory)  {
        File file = new File(dataStoreDirectory, "email");
        try {
            return new String(Files.readAllBytes(Paths.get(file.toURI())), "UTF-8");
        } catch (IOException ex) {
            log.error(null, ex);
            return null;
        }
    }

    public static boolean saveEmail(File dataStoreDirectory, String email) {
        File file = new File(dataStoreDirectory, "email");
        try {
            //If the constructor throws an exception, the finally block will NOT execute
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            try {
                writer.write(email);
            } finally {
                writer.close();
            }
            return true;
        } catch (IOException ex){
            log.error(null, ex);
            return false;
        }
    }

    public static void logoutGmail() {
        File credential = new File(getGmailDataDirectory(), "StoredCredential");
        File email = new File(getGmailDataDirectory(), "email");
        credential.delete();
        email.delete();
    }

    public static Pair<Pair<Credential, String>, Boolean> authorizeGmail() throws Exception {
        // Ask for only the permissions you need. Asking for more permissions will
        // reduce the number of users who finish the process for giving you access
        // to their accounts. It will also increase the amount of effort you will
        // have to spend explaining to users what you are doing with their data.
        // Here we are listing all of the available scopes. You should remove scopes
        // that you are not actually using.
        Set<String> scopes = new HashSet<>();

        // We would like to display what email this credential associated to.
        scopes.add("email");

        scopes.add(GmailScopes.GMAIL_SEND);

        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(Utils.JSON_FACTORY,
            new InputStreamReader(Utils.class.getResourceAsStream("/assets/authentication/gmail/client_secrets.json")));

        return authorize(clientSecrets, scopes, getGmailDataDirectory());
    }

    /** Authorizes the installed application to access user's protected data.
     * @return 
     * @throws Java.lang.Exception */
    private static Pair<Pair<Credential, String>, Boolean> authorize(GoogleClientSecrets clientSecrets, Set<String> scopes, File dataStoreDirectory) throws Exception {
        // Set up authorization code flow.

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets, scopes)
            .setDataStoreFactory(new FileDataStoreFactory(dataStoreDirectory))
            .build();
        // authorize
        return new MyAuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static Gmail getGmail(Credential credential) {
        Gmail service = new Gmail.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("JStock").build();
        return service;        
    }
}

OAuth2認証のユーザーフレンドリーな方法を提供するために、JavaFXを使用して、次の入力ダイアログを表示しました

enter image description here

ユーザーフレンドリーなoAuth2ダイアログを表示するためのキーは、 MyAuthorizationCodeInstalledApp.Java および SimpleSwingBrowser.Java にあります。

95
Cheok Yan Cheng

次のコードは私のために働いた。

import Java.io.UnsupportedEncodingException;
import Java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {

    public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "yourpassword";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.Host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

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

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler,"
                + "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
45
MobiDev
import Java.util.Date;
import Java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendEmail extends Object{

public static void main(String [] args)
{

    try{

        Properties props = new Properties();
        props.put("mail.smtp.Host", "smtp.mail.yahoo.com"); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true"); 
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("[email protected]", "password");
            }
        });

        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        msg.setFrom( new InternetAddress( "[email protected]" ) );
        msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse("[email protected]") );
        msg.setSentDate( new Date());
        msg.setSubject( "Hello World!" );

        //--[ Create the body of the mail
        msg.setText( "Hello from my first e-mail sent with JavaMail" );

        //--[ Ask the Transport class to send our mail message
        Transport.send( msg );

    }catch(Exception E){
        System.out.println( "Oops something has gone pearshaped!");
        System.out.println( E );
    }
}
}

必要なjarファイル

ここをクリック-外部ジャーを追加する方法

17
Kirit Vaghela

短い答え-いいえ。

長い答え-いいえ、コードはローカルマシンで実行され、ポート25でリッスンするSMTPサーバーの存在に依存するため、SMTPサーバー(技術的にはMTAまたはメール転送エージェント)はメールユーザーエージェントとの通信を担当します。 (MUA、この場合はJavaプロセス)送信メールを受信します。

現在、MTAは通常、特定のドメインのユーザーからメールを受信する役割を担っています。したがって、ドメインgmail.comの場合、メールユーザーエージェントの認証と、GMailサーバー上の受信ボックスへのメールの転送を担当するのはGoogleメールサーバーです。 GMailがオープンメールリレーサーバーを信頼するかどうかはわかりませんが、Googleに代わって認証を実行し、GMailサーバーにメールをリレーするのは確かに簡単な作業ではありません。

JavaMailを使用してGMailにアクセスする際の JavaMail FAQ を読むと、ホスト名とポートがたまたまGMailサーバーを指していることに気付くでしょう。 。ローカルマシンを使用する場合は、中継または転送を実行する必要があります。

SMTPに関してはどこにでも行きたいのであれば、おそらくSMTPプロトコルを深く理解する必要があるでしょう。 SMTPに関するウィキペディアの記事 から始めることができますが、さらに進歩するには実際にSMTPサーバーに対するプログラミングが必要になります。

10
Vineet Reynolds

メールを送信するにはSMTPサーバーが必要です。自分のPCにローカルにインストールできるサーバーがあります。または、多くのオンラインサーバーのいずれかを使用できます。よく知られているサーバーの1つはGoogleのサーバーです。

Simple Java Mail の最初の例を使用して、許可された Google SMTP構成 をテストしました。

    final Email email = EmailBuilder.startingBlank()
        .from("lollypop", "[email protected]")
        .to("C.Cane", "[email protected]")
        .withPlainText("We should meet up!")
        .withHTMLText("<b>We should meet up!</b>")
        .withSubject("hey");

    // starting 5.0.0 do the following using the MailerBuilder instead...
    new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
    new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
    new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);

さまざまなポートとトランスポート戦略(必要なすべてのプロパティを処理します)に注意してください。

不思議なことに、Googleの指示 そうでない場合 にもかかわらず、Googleはポート25でもTLSを必要とします。

6
Benny Bottema

これが投稿されてからかなりの時間が経ちました。しかし、2012年11月13日の時点で、ポート465が引き続き機能することを確認できます。

このフォーラム に関するGaryMの回答を参照してください。これがもっと少数の人々に役立つことを願っています。

/*
* Created on Feb 21, 2005
*
*/

import Java.security.Security;
import Java.util.Properties;

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 GoogleTest {

    private static final String SMTP_Host_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "" };


    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.Sun.net.ssl.internal.ssl.Provider());

        new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
            emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully mail to All Users");
    }

    public void sendSSLMessage(String recipients[], String subject,
                               String message, String from) throws MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.Host", SMTP_Host_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxx", "xxxxxx");
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
}
4
Mukus

次のコードは非常にうまく機能します。javamail-1.4.5.jarでJavaアプリケーションとしてこれを試してください。

import javax.mail.*;
import javax.mail.internet.*;
import Java.util.*;

public class MailSender
{
final String senderEmailID = "[email protected]";
final String senderPassword = "typesenderpassword";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public MailSender(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.Host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
public static void main(String[] args)
{     
MailSender mailSender=new
MailSender("[email protected]",emailSubject,emailBody);
}
}
2
Gayathri Rajan

このコードは電子メールを送信するために機能しますか?

ええ、いや、エラーが発生しているので、一部を変更せずに。現在、localhostで実行されているSMTPサーバーを介してメールを送信しようとしていますが、実行していないため、ConnectExceptionです。

コードに問題がないと仮定すると(実際には確認しませんでした)、ローカルSMTPサーバーを実行するか、(リモートから)1つ(ISPから)を使用する必要があります。

コードについては、 FAQ に記載されているように、JavaMailダウンロードパッケージにサンプルがあります。

JavaMailの使用方法を示すサンプルプログラムはどこにありますか?

Q:JavaMailの使用方法を示すサンプルプログラムはどこで入手できますか?
A: JavaMailダウンロードパッケージ には、JavaMail API、SwingベースのGUIアプリケーション、単純なサーブレットのさまざまな側面を示す単純なコマンドラインプログラムなど、多くのプログラム例があります。ベースのアプリケーション、およびJSPページとタグライブラリを使用した完全なWebアプリケーション。

2
Pascal Thivent

これが実用的なソリューションです。保証されています

1)まず、メールの送信元であるGmailアカウントを開きます。たとえば、「 "[email protected]"」

2)以下のこのリンクを開きます https://support.google.com/accounts/answer/6010255?hl=en

3)[マイアカウントの[安全性の低いアプリ]セクションに移動する]をクリックします。オプション

4)次に電源を入れます

5)それだけです(:

ここに私のコードがあります

import javax.mail.*;
import javax.mail.internet.*;
import Java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass Word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.Host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}
2
Zulfiqar Ali

これを試してみてください。それは私のためにうまく機能します。メールを送信する前に、Gmailアカウントで安全性の低いアプリへのアクセスを許可する必要があることを確認してください。次のリンクに移動して、このJavaコードを試してください。
安全性の低いアプリでGmailをアクティブ化

Javax.mail.jarファイルとactivation.jarファイルをプロジェクトにインポートする必要があります。

これはJavaでメールを送信するための完全なコードです

import javax.mail.*;
import javax.mail.internet.*;
import Java.util.*;

public class SendEmail {

    final String senderEmail = "your email address";
    final String senderPassword = "your password";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "587";
    String receiverEmail = null;
    String emailSubject = null;
    String emailBody = null;

    public SendEmail(String receiverEmail, String Subject, String message) {
        this.receiverEmail = receiverEmail;
        this.emailSubject = Subject;
        this.emailBody = message;

        Properties props = new Properties();
        props.put("mail.smtp.user", senderEmail);
        props.put("mail.smtp.Host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        SecurityManager security = System.getSecurityManager();

        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);

            Message msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmail));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmail));
            Transport.send(msg);
            System.out.println("send successfully");
        } catch (Exception ex) {
            System.err.println("Error occurred while sending.!");
        }

    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderEmail, senderPassword);
        }
    }

    public static void main(String[] args) {
        SendEmail send = new SendEmail("receiver email address", "subject", "message");
    }

}
2

SMTPサーバーとの接続を設定する以外に、コードは機能します。メールを送信するには、実行中のメール(SMTP)サーバーが必要です。

変更したコードは次のとおりです。不要な部分をコメントアウトし、オーセンティケーターが必要になるようにセッション作成を変更しました。使用したいSMPT_HOSTNAME、USERNAME、およびPASSWORDを見つけるだけです(通常、インターネットプロバイダーが提供します)。

ローカルメールサーバーの実行はWindowsではそれほど簡単ではないため(Linuxでは明らかに簡単です)、私はいつも(私の知っているリモートSMTPサーバーを使用して)このようにします。

import Java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

//import javax.activation.*;

public class SendEmail {

    private static String SMPT_HOSTNAME = "";
    private static String USERNAME = "";
    private static String PASSWORD = "";

    public static void main(String[] args) {

        // Recipient's email ID needs to be mentioned.
        String to = "[email protected]";

        // Sender's email ID needs to be mentioned
        String from = "[email protected]";

        // Assuming you are sending email from localhost
        // String Host = "localhost";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.Host", SMPT_HOSTNAME);

        // Get the default Session object.
        // Session session = Session.getDefaultInstance(properties);

        // create a session with an Authenticator
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    to));

            // Set Subject: header field
            message.setSubject("This is the Subject Line!");

            // Now set the actual message
            message.setText("This is actual message");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
1
Adriaan Koster

実際、465は機能しますが、例外はSMTPポート25が開いていないためです。デフォルトではポート番号は25です。ただし、オープンソースとして利用可能なメールエージェントを使用して設定できます-

簡単にするために、次の構成を使用するだけで問題ありません。

// Setup your mail server
props.put("mail.smtp.Host", SMTP_Host); 
props.put("mail.smtp.user",FROM_NAME);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.EnableSSL.enable","true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
props.setProperty("mail.smtp.socketFactory.fallback", "false");  
props.setProperty("mail.smtp.port", "465");  
props.setProperty("mail.smtp.socketFactory.port", "465");

さらに:完全な作業例を最初から確認してくださいhere

1
Atif Imran

レビューのために作業用のgmail JavaクラスをPastebinに配置しました。「startSessionWithTLS」メソッドに特に注意を払うと、JavaMailを調整して同じ機能を提供できる場合があります。 http://Pastebin.com/VE8Mqkqp

1
Paul Gregoire

あなたと同じ例外がありました。この理由は、マシンでsmptサーバーが稼働していないことです(ホストがlocalhostであるため)。 Windows 7を使用している場合、SMTPサーバーはありません。ドメインを使用してダウンロードし、インストールして構成し、アカウントを作成する必要があります。私はhmailserverをsmtpサーバーとして使用し、ローカルマシンにインストールして構成しました。 https://www.hmailserver.com/download

1
Lasan