我想发送邮件而不用打扰用于传递的SMTP服务器.
所以JavaMail API对我不起作用,因为我必须指定要连接的SMTP服务器.
我希望图书馆通过查询邮件地址域的MX记录,自行查找哪个SMTP服务器负责哪个电子邮件地址.
我正在寻找像阿司匹林这样的东西.不幸的是我不能使用Aspirin本身,因为开发已经停止了2004,并且库无法正确地与现代垃圾邮件强化服务器通信.
詹姆斯的可嵌入版本可以完成任务.但我还没有找到关于这是否可行的文件.
或者有没有人知道我可以使用的其他库?
一种可能的解决方案:自己获取MX记录并使用JavaMail API.
您可以使用dnsjava项目获取MX记录:
Maven2依赖:
dnsjava dnsjava 2.0.1
MX记录检索方法:
public static String getMXRecordsForEmailAddress(String eMailAddress) { String returnValue = null; try { String hostName = getHostNameFromEmailAddress(eMailAddress); Record[] records = new Lookup(hostName, Type.MX).run(); if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); } if (log.isTraceEnabled()) { // log found entries for debugging purposes for (int i = 0; i < records.length; i++) { MXRecord mx = (MXRecord) records[i]; String targetString = mx.getTarget().toString(); log.trace("MX-Record for '" + hostName + "':" + targetString); } } // return first entry (not the best solution) if (records.length > 0) { MXRecord mx = (MXRecord) records[0]; returnValue = mx.getTarget().toString(); } } catch (TextParseException e) { throw new RuntimeException(e); } if (log.isTraceEnabled()) { log.trace("Using: " + returnValue); } return returnValue; } private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException { String parts[] = mailAddress.split("@"); if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'"); return parts[1]; }
通过JavaMail代码发送邮件:
public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException { String smtpServer = getMXRecordsForEmailAddress(toAddress); // create session Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props); // create message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); msg.setSubject(subject); msg.setText(body); // send message Transport.send(msg); }