现在我正在使用这些依赖项。 编译组:“ javax.mail”,名称:“ mail”,版本:“ 1.4” testCompile组:“ 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);
}
});
}
}
答案 0 :(得分:0)
发生错误时,您应该捕获SMTPSendFailedException class EcomVerticle extends AbstractVerticle {
EComAppController eComAppController;
@Override
public void start() {
ApplicationContext context = new ClassPathXmlApplicationContext("application_context.xml");
this.eComAppController = (EComAppController) context.getBean("ecomAppController");
vertx.eventBus().consumer("ecom-question", (message) -> {
// eComAppController does something with the message
});
}
}
返回。此异常提供对方法javax.mail
的调用:
getReturnCode()
从SMTP服务器返回指示原因的返回码 对于失败。有关返回码的解释,请参见RFC 821。
查看RFC821的4.2.1和4.2.2节,您将找到错误代码的定义。因此,在您的程序中,您应该具有以下内容:
public int getReturnCode()