【发布时间】:2018-05-10 06:45:01
【问题描述】:
我正在为我的一门课程做一个期末项目,该程序旨在向代码中的地址发送电子邮件。我知道大部分代码是如何工作的,只是在理解密码身份验证以及如何连接到 SMTP 服务器和使用特定端口方面遇到了麻烦。代码的问题是它在运行时没有发送电子邮件,也没有给出任何错误消息。任何帮助将非常感激。这是代码。
package application;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main (String [] args) {
String host="smtp.gmail.com";
final String user="myemail@gmail.com";
final String password="password";
String to="targetemail.com";
//imported code
Properties props = new Properties();
props.put("mail.smtp.socketfactory.port", "465");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//imported code
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Dwight from the future");
message.setText("At 8:00, someone poisons the coffee. Do NOT drink
it.");
Transport.send(message);
System.out.println("message sent!");
}
catch (MessagingException mex)
{
System.out.println("Error: unable to send message....");
mex.printStackTrace();
}
}
}
【问题讨论】:
-
请检查 https: security.. 因为几乎所有的 smtp 服务器都使用 ssl 协议
-
@VedPrakash 他正在使用端口 465,即 smtps。
-
在您的代码中,
to不是电子邮件地址,而是域。不过,我觉得奇怪的是您不会看到错误消息。 -
在您的代码中修复这些common JavaMail mistakes 并查看这些Gmail instructions in the JavaMail FAQ。
标签: java api email jakarta-mail