我想从我的java应用程序向gmail帐户发送电子邮件我使用了以下代码和javaMail API,但Gmail不接受用户名和密码以及抛出的异常 任何人都可以帮助我如何解决这个问题?
MailService.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);
}
}
}
答案 0 :(得分:3)
为了能够通过您的Gmail帐户发送邮件,您应该在Google帐户安全设置中允许不安全的应用程序(您的应用程序是通过gmail的观点)。
UPD: 此外,如果要查看调试消息,请使用下一个java邮件属性:
props.put("mail.debug", "true");
它可以帮助您了解幕后发生的事情。
答案 1 :(得分:0)
您可以尝试允许不安全的应用程序,它对我有用。
Gmail帐户的步骤:
有关Gmail和G-Suite,请参见this link。