我正在处理从我的应用程序发送gmail的问题,我有以下代码:
public class Notificator {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("r","");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
我得到以下错误:线程中出现异常" main" java.lang.RuntimeException:javax.mail.AuthenticationFailedException:连接失败
因此我启用了安全性较低的设备,并在防火墙中启用了intellij。
编辑:是的我有正确的信誉,只是在放到这里之前删除它们。
答案 0 :(得分:1)
您需要指定Gmail帐户详细信息(电子邮件地址和密码),否则您将始终收到授权错误。
这是我之前使用过的一个样本:
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("youremailaddress@gmail.com");
javaMailSender.setPassword("GMAIL PASSWORD HERE");
javaMailSender.setJavaMailProperties(getMailProperties());
return javaMailSender;
}
private Properties getMailProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp"));
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.debug", "false");
return properties;
}
JavaMailSender javaMailSender = getJavaMailSender();
private void sendEmail(){
javaMailSender.send((MimeMessage mimeMessage) -> {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setFrom("from@no-spam.com");
message.setTo("to@no-spam.com");
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
});
}
答案 1 :(得分:1)
检查正确的属性:
Hello.vue