使用Gmail发送电子邮件

时间:2019-01-16 14:44:40

标签: java smtp gmail javamail

我无法再使用Java Mail API从Gmail帐户发送邮件。我怀疑应该对安全性进行一些更改。

我有这个简单的代码:

public static void generateAndSendEmail() throws AddressException, MessagingException {

    // Step1
    System.out.println("\n 1st ===> setup Mail Server Properties..");
    mailServerProperties = System.getProperties();
    mailServerProperties.put("mail.smtp.port", "587");
    mailServerProperties.put("mail.smtp.auth", "true");
    mailServerProperties.put("mail.smtp.starttls.enable", "true");
    System.out.println("Mail Server Properties have been setup successfully..");

    // Step2
    System.out.println("\n\n 2nd ===> get Mail Session..");
    getMailSession = Session.getDefaultInstance(mailServerProperties, null);
    generateMailMessage = new MimeMessage(getMailSession);
    generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("me@gmail.com"));

    generateMailMessage.setSubject("Greetings from Me..");
    String emailBody = "Test email using JavaMail API example.");
    generateMailMessage.setContent(emailBody, "text/html");
    System.out.println("Mail Session has been created successfully..");

    // Step3
    System.out.println("\n\n 3rd ===> Get Session and Send mail");
    Transport transport = getMailSession.getTransport("smtp");

    // Enter your correct gmail UserID and Password
    transport.connect("smtp.gmail.com", "my gmail username", "my password");
    transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
    transport.close();
}

我知道我拥有正确的凭据来代替my gmail usernamemy password,但仍然出现异常:

Exception in thread "main" javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:319)
at javax.mail.Service.connect(Service.java:169)
...

我什至为不太安全的应用启用了访问权限,但仍然没有帮助。

0 个答案:

没有答案