gpt4 book ai didi

java - 在java中使用gmail帐户发送邮件

转载 作者:行者123 更新时间:2023-11-30 03:27:34 27 4
gpt4 key购买 nike

我尝试使用 Gmail SMTP 向任何 Gmail 帐户发送一封简单的电子邮件。出现以下错误。

javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:587;
嵌套异常是:
java.net.ConnectException:连接超时:连接

我的代码是

package common;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPMessage;

public class SimpleMail{

/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {

String to="mymailid@gmail.com";
String subject="New Mail";

String msg="test test";

final String user="gmailuser";
final String pass="gmailpassowd";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); //this is optional
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");



Session session = Session.getInstance(props,new javax.mail.Authenticator() {

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});

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

Transport.send(message);
System.out.println("Mail sent..");
}catch(Exception e)
{
System.out.println(e);
}
}



}

最佳答案

检查您的端口。来自 Google 的支持:

If you tried configuring your SMTP server on port 465 (with SSL) and port 587 (with TLS), but are still having trouble sending mail, try configuring your SMTP to use port 25 (with SSL).

来源:https://support.google.com/mail/answer/78775?hl=en

所以,尝试使用端口 25 看看会发生什么。

关于java - 在java中使用gmail帐户发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29820170/

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