我想通过 Java 代码发送电子邮件。我在我的库中添加了以下 .JAR:log4j.jar、smtp.jar、mailapi.jar、ctivation.jar。我的 Java 类如下所示:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
String to = "abcd@gmail.com";
String from = "web@gmail.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.auth", "true");
SmtpAuthenticator authentication = new SmtpAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
.getInstance(properties, authentication));
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress(to));
msg.setSubject("Subject");
msg.setText("Working fine..!");
System.out.println("fine1 !!");
Transport transport = Session.getDefaultInstance( properties , null).getTransport("smtp");
System.out.println("fine2 !!");
transport.connect("smtp.gmail.com" , 465 , "username", "password");
System.out.println("fine3 !!");
Transport.send(msg);
System.out.println("fine!!");
}
catch(Exception exc) {
System.out.println(exc);
}
}
}
我的 SmtpAuthenticator 类:
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class SmtpAuthenticator extends Authenticator {
public SmtpAuthenticator() {
super();
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = "user";
String password = "password";
if ((username != null) && (username.length() > 0) && (password != null)
&& (password.length() > 0)) {
return new PasswordAuthentication(username, password);
}
return null;
}
}
当我运行我的 Java 应用程序类时,它会打印: 很好! 很好!
它挂起。我怎样才能摆脱这个问题?
最佳答案
问题出在这一行:
transport.connect("smtp.gmail.com" , 465 , "username", "password");
465 是 smtp over ssl (smtps) 的端口,因此要么使用端口 25:
transport.connect("smtp.gmail.com" , 25 , "username", "password");
或者改用smtps
Transport transport = Session.getDefaultInstance( properties , null).getTransport("smtps");
transport.connect("smtp.gmail.com" , 465, "username", "password");
关于java - 使用 Java 发送电子邮件,连接到 gmail 主机挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24129151/