gpt4 book ai didi

java 邮件 gmail

转载 作者:搜寻专家 更新时间:2023-10-31 20:14:12 24 4
gpt4 key购买 nike

我想通过 google 的 smtp 服务器在我的 java 程序中发送邮件,但似乎无法发送邮件。有人可以告诉我为什么吗?

这是发送邮件的函数:

     public void sendMail(){
String from = "xxx@gmail.com";
String to = "xxx@hotmail.com";
String subject = "Test";
String message = "A test message";

SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}

这是类

public class SendMail {
private String from;
private String to;
private String subject;
private String text;

public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}

public void send(){

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.setProperty( "mail.smtp.port", "587" );
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);

new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "MyPasswordGoesHere");
}
};

try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(text);

Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

提前致谢!

最佳答案

好的,我用这段代码解决了这个问题: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

关于java 邮件 gmail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12371761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com