5

我想通过谷歌的 smtp 服务器在我的 java 程序中发送邮件,但它似乎卡在发送邮件上。有人能告诉我为什么吗?

这是发送邮件的功能:

     public void sendMail(){
            String from = "xxx@gmail.com";
    String to = "xxx@hotmail.com";
    String subject = "Test";
    String message = "A test message";

    SendMail sendMail = new SendMail(from, to, subject, message);
    sendMail.send();
}

这就是课堂

public class SendMail {
private String from;
private String to;
private String subject;
private String text;

public SendMail(String from, String to, String subject, String text){
    this.from = from;
    this.to = to;
    this.subject = subject;
    this.text = text;
}

public void send(){

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.setProperty( "mail.smtp.port", "587" );
    props.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getDefaultInstance(props);

    new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(from, "MyPasswordGoesHere");
    }
      };

  try {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(text);

    Transport.send(message);
    System.out.println("message sent successfully");
    } catch (MessagingException e) {
    throw new RuntimeException(e);
     }
      }
        }

提前致谢!

4

2 回答 2

5

好的,我使用以下代码解决了它: http ://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

于 2012-09-11T14:38:34.517 回答
0

我的博客文章中,我尝试举例说明使用 Java 通过 Gmail 的 SMTP 服务器发送电子邮件。这里有 2 个示例代码。其中一个使用 Java Mail API,而另一个利用 Apache Commons Mail 库。

于 2015-06-17T15:56:37.560 回答