邮件 API : Username and Password not accepted (Gmail)

标签 java authentication gmail jakarta-mail

我想从我的 java 应用程序发送电子邮件到 gmail 帐户我使用了以下代码和 javaMail API,但是 Gmail 不接受用户名和密码并抛出异常 谁能帮我解决这个问题?

邮件服务.java

public class MailService {

    String email;
    String content;
    public void sendMail(String email,String content)
    {
        this.email=email;
        this.content=content;
        // Recipient's email ID needs to be mentioned.
          String to = email;

          // Sender's email ID needs to be mentioned
          String from = senderemail@gmail.com;
          final String username = "myusername";//change accordingly
          final String password = "*******";//change accordingly

          // Assuming you are sending email through relay.jangosmtp.net
          String host = "smtp.gmail.com";

          Properties props = new Properties();
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.starttls.enable", "true");
          props.put("mail.smtp.host", host);
          props.put("mail.smtp.port", "587");

          // Get the Session object.
          Session session = Session.getInstance(props,
             new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(username, password);
           }
             });

          try {
           // Create a default MimeMessage object.
           Message message = new MimeMessage(session);

           // Set From: header field of the header.
           message.setFrom(new InternetAddress(from));

           // Set To: header field of the header.
           message.setRecipients(Message.RecipientType.TO,
                   InternetAddress.parse(to));

           // Set Subject: header field
           message.setSubject("Did you get my message?");

           // Now set the actual message
           message.setText(content);

           // Send message
           Transport.send(message);

           System.out.println("Sent message successfully....");

          } catch (MessagingException e) {
             throw new RuntimeException(e);
          }
       }
    }

最佳答案

为了能够通过您的 gmail 帐户发送邮件消息,您应该在 Google 帐户安全设置中允许不安全的应用程序(从 gmail 的角度来看,您的应用程序是这样的)。 enter image description here

更新: 此外,如果您想查看调试消息,请使用下一个 java 邮件属性:

props.put("mail.debug", "true");

它可以帮助您了解幕后发生的事情。

关于邮件 API : Username and Password not accepted (Gmail),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43406528/

相关文章:

powershell - 通过 Gmail SMTP 从 Powershell 发送邮件

java - 无法获取 'https://google.bintray.com/.../maven-metadata.xml' 。从服务器 : Forbidden 收到状态码 403

java - Selenium 2 chrome 驱动程序首选项 java 等同于 RubyBindings

java - 将github android源码导入到eclipse

java - Jboss mysql 数据源

java - Spring Security 登录页面

android - 用于从 Android 上的 gmail 应用程序下载附件的 Intent 过滤器

bash - bash脚本问题将ssh登录发送到Mattermost

windows - 使用socks4时的认证方式

php - 如何获取 Gmail 未读邮件数