Java Mail:使用 TLS 通过 gmail 发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10945511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:11:30  来源:igfitidea点击:

Java Mail: sending email via gmail with TLS

javaemailgmailjavamail

提问by gadon

I'm trying to send simple email with my java application, but when I will execute sending mail, I get just "220 2.0.0 Ready to start TLS" on console and nothing is happening later. Here is method code:

我正在尝试使用我的 java 应用程序发送简单的电子邮件,但是当我执行发送邮件时,我在控制台上只收到“220 2.0.0 Ready to start TLS”,之后什么也没有发生。下面是方法代码:

try
    {
        /** Recipient address **/
        String messageRecipient = "@live.com";

        String pass = "";
        /** sender address **/
        String messageSender = "@gmail.com";

        /** get my properties **/
        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.user", messageSender);
        properties.put("mail.smtp.password",  pass);
        properties.put("mail.debug", "true");
        properties.put("mail.smtp.debug", "true");
        properties.put("mail.smtp.port", "587");

        /** get default session object **/
        Session session = Session.getDefaultInstance(properties,// null);
                new javax.mail.Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("@gmail.com", "");
            }
        });

        try
        {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(messageSender));

            //set to: header field of the header
            message.addRecipient(Message.RecipientType.TO, 
                            new InternetAddress(messageRecipient));
            //set subject: header field
            message.setSubject("Welcome to java mail!");

            //send message
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.gmail.com", 587, messageSender, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            System.out.println(Errors.MESSAGE_SENT_SUCCESSFULLY);
            return null;
        }
        catch(MessagingException mex)
        {
            return Errors.MESSAGE_NOT_SENT;
        }
    }
    catch(Exception e)
    {
        return Errors.FILE_NOT_FOUND;
    }
}

And debug output in console:

并在控制台中调试输出:

     DEBUG: JavaMail version 1.4.5
    DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
    DEBUG: Tables of loaded providers
    DEBUG: Providers Listed By Class Name:         {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSS        LTransport,Sun Microsystems, Inc],                         com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTranspo        rt,Sun Microsystems, Inc],         com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Su        n Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Su        n Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun                 Microsystems, Inc],         com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun         Microsystems, Inc]}
    DEBUG: Providers Listed By Protocol:         {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],         imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],         smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun                 Microsystems, Inc],         pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun         Microsystems, Inc],         pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun         Microsystems, Inc],         smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun                 Microsystems, Inc]}
    DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
    DEBUG: getProvider() returning         javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
    220 mx.google.com ESMTP e20sm6680361wiv.7
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

    EHLO gadon-Komputer
    250-mx.google.com at your service, [83.22.91.238]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250 ENHANCEDSTATUSCODES
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "STARTTLS", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    STARTTLS
    220 2.0.0 Ready to start TLS
    DEBUG: getProvider() returning         javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
    DEBUG SMTP: useEhlo true, useAuth true
    DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
    220 mx.google.com ESMTP et10sm6688757wib.2
    DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

    EHLO gadon-Komputer
    250-mx.google.com at your service, [83.22.91.238]
    250-SIZE 35882577
    250-8BITMIME
    250-STARTTLS
    250 ENHANCEDSTATUSCODES
    DEBUG SMTP: Found extension "SIZE", arg "35882577"
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "STARTTLS", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    STARTTLS
    220 2.0.0 Ready to start TLS

Can somebody tell me what's wrong with this? I read houndreds topics about javamail but I couldn't find answer for my problem.. Nothing is changing in output if I will change password.

有人能告诉我这有什么问题吗?我阅读了有关 javamail 的 houndreds 主题,但我找不到我的问题的答案.. 如果我更改密码,输出中没有任何变化。

回答by Bill Shannon

You can simplify your code using the Gmail example in the JavaMail FAQ. (Don't set the port number, use the "smtps" protocol, and get rid of the Authenticator.) Also, change getDefaultInstance to getInstance.

您可以使用JavaMail FAQ 中Gmail 示例来简化您的代码。(不要设置端口号,使用“smtps”协议,去掉Authenticator。)另外,把getDefaultInstance改为getInstance

回答by balaji palamadai

The below code is a simple implementation of Email using java, I wrote this after referring the docs of java mail API and it works perfectly..

下面的代码是一个简单的用java实现的Email,我参考java mail API的文档写的,效果很好..

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

public class Email
{
public Email()
    {
try {
    String host = "smtp.gmail.com";
    String username = "[email protected]";
    String password = "XXXXXX";
    String body = "This is the message body.";
    String subject = "This is the message subject."; 
    //Set the properties
    Properties props = new Properties();
    props.put("mail.smtps.auth", "true");
    // Set the session here
    Session session = Session.getDefaultInstance(props);
    MimeMessage msg = new MimeMessage(session);
    // set the message content here
      msg.setSubject(subject);
      msg.setText(body);
      msg.setFrom(new InternetAddress(username));
      msg.addRecipient(Message.RecipientType.TO, 
              new InternetAddress(username));
    Transport t = session.getTransport("smtps");

    t.connect(host, username, password);
    t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    }
   catch (Exception e) {
   e.printStackTrace();
   }
 finally {

    }
     }
    public static void main(String[] args)
    throws Exception {
            new Email();
    }

}

回答by Omar Jaafor

I am a bit late, but I faced a similar issue and wanted to post my feedback. Sometimes, the port is blocked by an antivirus. Avast for example does that.

我有点晚了,但我遇到了类似的问题,想发布我的反馈。有时,该端口被防病毒软件阻止。例如,Avast 就是这样做的。

回答by Gesuino

if you don't I suggest you to use Spring to simply the Send Email process.

如果您不这样做,我建议您使用 Spring 来简化发送电子邮件过程。

To send a simple email you have to write this:

要发送一封简单的电子邮件,您必须这样写:

 `import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.mail.MailException;
  import org.springframework.mail.MailSender;
  import org.springframework.mail.SimpleMailMessage;`
.........
@Autowired
private MailSender mailSender;

SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo("[email protected]");
            mailMessage.setFrom("[email protected]");
            mailMessage.setSubject(this.subject);
            mailMessage.setText(text.toString());
            try {
                this.mailSender.send(mailMessage);
                logger.info("Email inviata con successo");
            }
            catch (MailException ex) {
                // just log it and go on
                logger.warn("An exception occured when trying to send email", ex);
            }

And in your applicationContext.xml

在你的 applicationContext.xml

 <!-- MailSender used by EmailAdvice -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="port" value="${mail.port}" />
        <property name="username" value="${mail.username}" />
        <property name="password" value="${mail.password}" />

        <property name="javaMailProperties">
           <props>
                  <prop key="mail.smtp.auth">true</prop>
                  <prop key="mail.smtp.starttls.enable">true</prop>
               </props>
        </property>
    </bean>

For more info follow this simple tutorial http://www.mkyong.com/spring/spring-sending-e-mail-via-gmail-smtp-server-with-mailsender/

有关更多信息,请遵循这个简单的教程http://www.mkyong.com/spring/spring-sending-e-mail-via-gmail-smtp-server-with-mailsender/

回答by Logan

Try by removing properties.put("mail.smtp.starttls.enable", "true"), change the port to 465 and add these two properties:

尝试通过删除properties.put("mail.smtp.starttls.enable", "true"),将端口更改为 465 并添加以下两个属性:

props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");