我想通过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应用程序类时,它会打印: fine1 !! fine2 !!
它挂了。我怎样摆脱这个问题?
答案 0 :(得分:4)
问题在于这一行:
transport.connect("smtp.gmail.com" , 465 , "username", "password");
465是smtp超过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");