我正在尝试使用 javax 发送 eamil。 我的代码如下:
private String emailSender(String emailTo, String emailFrom, String message, String subject, String password) {
String status = "failed";
try {
String ccEmail = "";
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtps.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtps.auth", "true");
props.put("mail.smtps.quitwait", "false");
Session session = Session.getInstance(props, null);
// -- Create a new message --
final MimeMessage msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(emailFrom));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo, false));
if (ccEmail.length() > 0) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
}
msg.setSubject(subject);
msg.setText(message, "utf-8");
msg.setSentDate(new Date());
SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
String host = StringUtils.substringAfter(emailFrom, "@");
String emailName = StringUtils.substringBefore(emailFrom, "@");
t.connect("smtp." + host, emailName, password);
t.sendMessage(msg, msg.getAllRecipients());
t.close();
status = "Sent";
} catch (Exception e) {
LOGGER.error("error with sending email ", e);
}
return status;
}
一般来说,它可以正常工作。我可以通过 gmail 帐户或 yahoo 发送...但是当我尝试从 contact@vayg.com 帐户发送时,遇到如下未知主机异常:
javax.mail.MessagingException: Unknown SMTP host: smtp.vayg.com;
有什么解决办法吗?
最佳答案
您假设主机有一个三级域,并且始终在其前面加上“smtp”前缀。
但情况可能并非总是如此。 smtp 主机名可以是任何名称。
关于javax未知主机异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26893960/