java 通过 SMTP 发送电子邮件时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27614793/
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-11-02 12:07:36  来源:igfitidea点击:

Error in sending email through SMTP

javaemail

提问by user3868730

I'm trying to send an email through Java Code using gmail as the SMTP. But getting an exception as below. Can you pls let me know why is it not able to find the gmail host. I'm working in office network, not sure if some firewall is stopping it from sending. If yes, what is the way out ?

我正在尝试使用 gmail 作为 SMTP 通过 Java 代码发送电子邮件。但得到如下异常。你能告诉我为什么找不到 gmail 主机吗?我在办公室网络中工作,不确定是否有防火墙阻止它发送。如果是,出路是什么?

Exception in thread "main" com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 586; timeout -1;
  nested exception is:
    java.net.UnknownHostException: smtp.gmail.com
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2053)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
    at javax.mail.Service.connect(Service.java:364)
    at javax.mail.Service.connect(Service.java:245)
    at mail.JavaEmail.sendEmail(JavaEmail.java:72)
    at mail.JavaEmail.main(JavaEmail.java:22)
Caused by: java.net.UnknownHostException: smtp.gmail.com

Java Source Code :

Java源代码:

package mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
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 JavaEmail
{
    Session mailSession;

    public static void main(String args[]) throws AddressException,    MessagingException
    {
        JavaEmail javaEmail = new JavaEmail();
        javaEmail.setMailServerProperties();
        javaEmail.draftEmailMessage();
        javaEmail.sendEmail();
    }

    private void setMailServerProperties()
    {
        Properties emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", "586");
        emailProperties.put("mail.smtp.auth", "true");
        emailProperties.put("mail.smtp.starttls.enable", "true");
        mailSession = Session.getDefaultInstance(emailProperties, null);
    }

    private MimeMessage draftEmailMessage() throws AddressException, MessagingException
    {
        String[] toEmails = { "[email protected]" };
        String emailSubject = "Test email subject";
        String emailBody = "This is an email sent by JAVA Code";
        MimeMessage emailMessage = new MimeMessage(mailSession);
        /**
         * Set the mail recipients
         * */
        for (int i = 0; i < toEmails.length; i++)
        {
            emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
        }
        emailMessage.setSubject(emailSubject);
        /**
         * If sending HTML mail
         * */
        emailMessage.setContent(emailBody, "text/html");
        /**
         * If sending only text mail
         * */
        //emailMessage.setText(emailBody);// for a text email
        return emailMessage;
    }

    private void sendEmail() throws AddressException, MessagingException
    {
        /**
         * Sender's credentials
         * */
    String fromUser = "[email protected]";
        String fromUserEmailPassword = "*****";

        String emailHost = "smtp.gmail.com";
        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromUser, fromUserEmailPassword);
        /**
         * Draft the message
         * */
        MimeMessage emailMessage = draftEmailMessage();
        /**
         * Send the mail
         * */
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        System.out.println("Email sent successfully.");
    }
}

回答by John Cipponeri

You're connecting to the wrong port. Google's SMTP server for TLS is 587. You can see more information on this here: http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm

您连接到错误的端口。用于 TLS 的 Google SMTP 服务器是587。您可以在此处查看更多信息:http: //email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm

回答by Darshil Shah

this may help you

这可能会帮助你

Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "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");   
        props.setProperty("mail.smtp.quitwait", "false");   

        session = Session.getDefaultInstance(props, this);

回答by Anptk

The following code may help you to solve your problem, its working........

以下代码可以帮助您解决您的问题,它的工作原理......

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

public class Email {

private static String USER_NAME = "username";  // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "password"; // GMail password

private static String RECIPIENT = "[email protected]";

public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";

sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";

props.put("mail.smtp.starttls.enable", "true");

props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");


Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);

try {


    message.setFrom(new InternetAddress(from));
    InternetAddress[] toAddress = new InternetAddress[to.length];

    // To get the array of addresses
    for( int i = 0; i < to.length; i++ ) {
        toAddress[i] = new InternetAddress(to[i]);
    }

    for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }



    message.setSubject(subject);
    message.setText(body);


    Transport transport = session.getTransport("smtp");


    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();

}
catch (AddressException ae) {
    ae.printStackTrace();
}
catch (MessagingException me) {
    me.printStackTrace();
  }
 }
} 

回答by ???? ??????

I had same issue. Changed host smtp.gmail.com to ip 74.125.133.109 and now it works well.

我有同样的问题。将主机 smtp.gmail.com 更改为 ip 74.125.133.109,现在运行良好。