【发布时间】:2011-02-12 17:57:10
【问题描述】:
我正在尝试使用 Java 发送电子邮件。通过阅读,我发现如果我使用 gmail 作为主机,我可以免费这样做并且它应该可以工作,对吗?
所以我在下面有我的代码,并且我正在尝试将自己的电子邮件发送给我朋友的电子邮件(我下面代码中的电子邮件已被更改以保护隐私)但是当我去发送/传输时抛出异常电子邮件(在 Transport.send(msg);) 行
抛出的输出/异常是:
javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:25; 嵌套异常是: java.net.ConnectException:连接超时:连接 应该成功: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 );
}
}
【问题讨论】: