我在编写一个java电子邮件发送程序。但是当我单击“发送”按钮时,按钮会出现挂起模式&程序仍在运行,但邮件没有发送。我找不到问题了。有人能帮我..。代码在下面。
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("myid@gmail.com", "password");
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myid@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("senderid@gmail.com"));
message.setSubject("Demo mail");
message.setText("Hello, world!");
Transport.send(message);
JOptionPane.showMessageDialog(this, "Message sent!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e);
}我的电子邮件帐户还没有启动2步验证服务.它也适用于outlook电子邮件发送软件。我测试过了。
但不工作在我的java程序。
发布于 2015-01-31 18:56:06
我认为应该扩展身份验证类。下面是一个对我有用的例子:
public class SendEmail {
public SendEmail () {}
public void send (String text){
String host = "smtp.gmail.com";
String username = "user@email.com";
String password = "password";
Properties props = new Properties();
// set any needed mail.smtps.* properties here
Session session = Session.getInstance(props, new GMailAuthenticator("user", "password"));
Message msg = new MimeMessage(session);
Transport t;
try {
msg.setText(text);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("stackkinggame@gmail.com", "Stack King"));
t = session.getTransport("smtps");
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
Gdx.app.log("Email", "Message sent successfully.");
}
catch (Exception e) {
e.printStackTrace();
}
}
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
}发布于 2015-02-01 04:03:00
首先,修复程序中的所有常见JavaMail错误。
其次,既然您使用的是Gmail,请确保您已经拥有了启用对不太安全的应用程序的支持。
最后,你需要提供比“它不起作用”更多的细节。JavaMail调试输出会有帮助的。
https://stackoverflow.com/questions/28255231
复制相似问题