【问题标题】:JavaMail API has trouble to work with the GmailJavaMail API 无法与 Gmail 配合使用
【发布时间】:2016-04-21 21:17:18
【问题描述】:

我正在编写http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html 的教程,该教程展示了如何使用 JavaMail API 发送电子邮件。

于是我写了如下代码sn-p

public class EmailSessionBean {

private int port = 465;
private String host = "smtp.gmail.com";
private String from = "xxx@gmail.com";
private boolean auth = true;
private String username = "xxx@gmail.com";
private String password = "mypassword";
private Protocol protocol = Protocol.SMTPS;
private boolean debug = true;

public void sendEmail(String to, String subject, String body) {

    // Create a Properties object to contain settings for 
    // the SMTP protocol provider.
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    switch (protocol) {
        case SMTPS:
            props.put("mail.smtp.ssl.enable", true);
            break;
        case TLS:
            props.put("mail.smtp.starttls.enable", true);
            break;
    }

    // If SMTP authentication is required you must set the mail.smtp.auth 
    // property and construct a Authenticator instance that returns 
    // a PasswordAuthentication instance with your username and password. 
    Authenticator authenticator = null;
    if (auth) {
        props.put("mail.smtp.auth", true);
        authenticator = new Authenticator() {
            private PasswordAuthentication pa
                    = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return pa;
            }
        };
    }

    //Create a Session instance using the Properties object 
    // and the Authenticator object.
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

    // Construct a MimeMessage instance, populate the message headers 
    // and content and then send the message
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
}
}

当我尝试使用 WEB APP 发送电子邮件时,Gmail 阻止我这样做并向我发送“已阻止登录尝试”。

附:我还在我的 Gmail 帐户中禁用了“访问不太安全的应用程序”。但在下一次尝试这样做时,Gmail 暂停了我的帐户。

任何有用的评论/解决方案将不胜感激。

【问题讨论】:

    标签: java email jakarta-ee gmail jakarta-mail


    【解决方案1】:

    确保您已经检查了here 列出的所有内容,尤其是DisplayUnlockCaptcha

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2014-09-13
      • 2010-12-06
      • 2014-05-29
      相关资源
      最近更新 更多