Edu*_*rch 10 java email smtp james
我想发送邮件而不用打扰用于传递的SMTP服务器.
所以JavaMail API对我不起作用,因为我必须指定要连接的SMTP服务器.
我希望图书馆通过查询邮件地址域的MX记录,自行查找哪个SMTP服务器负责哪个电子邮件地址.
我正在寻找像阿司匹林这样的东西.不幸的是我不能使用Aspirin本身,因为开发已经停止了2004,并且库无法正确地与现代垃圾邮件强化服务器通信.
詹姆斯的可嵌入版本可以完成任务.但我还没有找到关于这是否可行的文件.
或者有没有人知道我可以使用的其他库?
Edu*_*rch 15
一种可能的解决方案:自己获取MX记录并使用JavaMail API.
您可以使用dnsjava项目获取MX记录:
Maven2依赖:
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>2.0.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
通过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);
}
Run Code Online (Sandbox Code Playgroud)
这是完全错误的处理方式。
连接到互联网的任何人都可以使用某种“合法”的 SMTP 服务器来接收电子邮件的提交——您的 ISP、您的办公室等。
您想要利用杠杆,因为他们为您做了很多事情。
1)他们接受您的消息并负责处理该消息。当你放下它之后,它就不再是你的问题了。
2) 任何邮件反垃圾邮件技术均由服务器处理。更好的是,当/如果这些技术发生变化(域密钥有人吗?),服务器会处理它,而不是您的代码。
3) 作为该发送邮件系统的客户端,您已经拥有与该服务器通信所需的任何凭据。主要 SMTP 服务器通过身份验证、IP 范围等锁定。
4)你不是在重新发明轮子。利用您拥有的基础设施。您正在编写应用程序还是邮件服务器?设置邮件服务器是一项日常任务,通常很容易完成。互联网上所有那些偶然的“愚蠢”用户都设法设置了电子邮件。
| 归档时间: |
|
| 查看次数: |
7351 次 |
| 最近记录: |