gpt4 book ai didi

java - 发送电子邮件 : Problem when connecting to host

转载 作者:行者123 更新时间:2023-12-01 15:56:24 24 4
gpt4 key购买 nike

我正在尝试使用 Java 发送电子邮件。通过阅读,我发现如果我使用 gmail 作为主机,我可以免费执行此操作并且它应该可以工作,对吗?

所以我的代码如下,我正在尝试将我自己的电子邮件发送到我 friend 的电子邮件(出于隐私原因,我下面的代码中的电子邮件已被更改),但当我发送/传输时,我抛出异常电子邮件(位于 Transport.send(msg); 行)

抛出的输出/异常是:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25; nested exception is: java.net.ConnectException: Connection timed out: connect Should have succeeded: false

你认为我做错了什么?

/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
class SMTPAuthenticator extends javax.mail.Authenticator
{

public PasswordAuthentication getPasswordAuthentication()
{
String username = "myaccount@gmail.com";
String password = "xxxxxxx";
return new PasswordAuthentication(username, password);
}
}

public class SendEmail
{

public SendEmail()
{

}

public static boolean sendEmail( String from, String to[], String subject, String body )
{
try
{
boolean debug = false;

// Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com" ); // "smtp.jcom.net");
props.put("mail.smtp.auth", "true");

// create some properties and get the default Session
// Session session = Session.getDefaultInstance(props, null);
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);

// create a message
Message msg = new MimeMessage(session);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

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

// Optional : You can also set your custom headers in the Email if
// you Want
msg.addHeader("MyHeaderName", "myHeaderValue");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(body, "text/plain");

System.out.println( "1" );
Transport.send(msg);
System.out.println( "2" );
}
catch (Exception e)
{
System.out.println( e );
return false;
}

return true;
}

public static void main(String args[])
{
boolean res = SendEmail.sendEmail( "myaccount@gmail.com", new String[] {"x@y.com", "y@x.com.au"},
"Test", "Did it work?" );
System.out.println( "Should have succeeded: " + res );
}

}

最佳答案

Google 是您的 friend 。检查这个网站:http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

Gmail 仅接受使用 TLS 的安全连接,但您使用的是标准的非安全身份验证。

关于java - 发送电子邮件 : Problem when connecting to host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com