尝试使用java mail API发送电子邮件,我一直收到SMTPSendFailedException
,这是完整的错误:
org.eclipse.angus.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. d5-20020a170902c18500b00194c90ca320sm6172077pld.204 - gsmtp
at org.eclipse.angus.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2422)
at org.eclipse.angus.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1839)
at org.eclipse.angus.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1316)
字符串
下面是函数sendEmail()
public void sendEmail(List<String> to, String subject, String body){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.starttls.enable", true);
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username));
InternetAddress[] addresses = new InternetAddress[to.size()];
for (int i = 0; i < to.size(); i++) {
addresses[i] = new InternetAddress(to.get(i));
}
msg.setRecipients(Message.RecipientType.TO, addresses);
msg.setSubject(subject);
msg.setText(body, "utf-8");
msg.setSentDate(new Date());
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, appPassword);//CAUSES EXCEPTION
transport.sendMessage(msg, msg.getAllRecipients());
// transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
}
型username
和appPassword
是全局变量。
当我使用transport.send(msg)
而不是transport.sendMessage(msg, msg.getAllRecipients())
时,我会得到以下错误:
org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at org.eclipse.angus.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2258)
at org.eclipse.angus.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:753)
at jakarta.mail.Service.connect(Service.java:342)
at jakarta.mail.Service.connect(Service.java:222)
at jakarta.mail.Service.connect(Service.java:171)
at jakarta.mail.Transport.send0(Transport.java:230)
at jakarta.mail.Transport.send(Transport.java:100)
型
虽然我正在使用port 587
,但我得到了这个错误。我在java mail API中使用这个依赖项:
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.0.0</version>
</dependency>
型
- 我试过几乎所有的方法,从堆栈溢出和chatGPT,但找不到解决方案 *
1条答案
按热度按时间agyaoht71#
将端口号作为connect()方法的第二个参数发送。
transport.connect(host,587,username,password);