问题描述
现在,我正在使用这些依赖项。 编译组:“ javax.mail”,名称:“ mail”,版本:“ 1.4” test编译组:“ javax.mail”,名称:“ mail”,版本:“ 1.4”
当电子邮件发送失败时,我想获取错误代码(例如错误5.1.1)。 我可以从MessagingException获取此错误代码吗? 以及如何获得它?
import javax.mail.*;
import org.springframework.stereotype.Component;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;
@Component
public class SendEmailClient
{
/**
* send email to receiver.
*/
public void send(String _sender, String _receiver, String _subject, String _subjectCharset, String _body, String _bodyContentType, String _bodyCharset)
{
MimeMessage message = new MimeMessage(getSmtpSession());
Multipart multipartMessage = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
try {
message.setFrom(new InternetAddress(_sender));
message.setRecipients(Message.RecipientType.TO, _receiver);
message.setSubject(_subject,_subjectCharset);
bodyPart.setContent(_body, "text/" +_bodyContentType + "; charset=" + _bodyCharset);
multipartMessage.addBodyPart(bodyPart);
message.setContent(multipartMessage);
Transport.send(message);
} catch (MessagingException _e) {
}
}
/**
* Get smtp session.
* @return
*/
private Session getSmtpSession()
{
final String username = "email";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
return Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
}
1楼
发生错误时,您应该捕获 javax.mail
返回。
此异常提供对方法getReturnCode()
的调用:
public int getReturnCode()
从SMTP服务器返回指示失败原因的返回码。 有关返回码的解释,请参阅RFC 821。
查看 4.2.1和4.2.2节,您将找到错误代码的定义。 因此,在您的程序中,您应该具有以下内容:
try
{
//connect,...
}
catch(SMTPSendFailedException e)
{
int errorCode = e.getReturnCode(); //f.e: 401
//check what error message the code relates, print it, etc..
}