共计 1730 个字符,预计需要花费 5 分钟才能阅读完成。
环境 :jdk8,maven
需要的 pom,高版本发送会验证 spf,这个不会
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.6</version>
</dependency>
纯文本邮件内容发送
public class MailUtil {
private final static String FROM = "**@**.com";
public static void main(String[] args) {
String mail ="***@**.com";
String smtp = getSmtpByEmail(mail);
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", smtp);
props.put("mai.smtp.auth", "false");
Session session = Session.getInstance(props, null);
MimeMessage msg= new MimeMessage(session);
try {msg.setFrom(FROM);
msg.setSubject("紧急通知","gb2312");
Multipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText("你的余额已不足", "gb2312");
multipart.addBodyPart(bodyPart);
msg.setContent(multipart);
msg.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(mail));
Transport.send(msg);
System.out.println("send success");
} catch (MessagingException e) {e.printStackTrace();
}
}
private static String getSmtpByEmail(String mail){Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put(Context.PROVIDER_URL, "dns://");
hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
String domain = mail.substring(mail.lastIndexOf('@') + 1);
Attributes attrs = null;
String smtp=null;
try {InitialDirContext dirContext = new InitialDirContext(hashtable);
attrs = dirContext.getAttributes(domain, new String[]{"MX"});
NamingEnumeration<? extends Attribute> attrsAll = attrs.getAll();
while(attrsAll.hasMore()) {Attribute next = attrsAll.next();
for(int i=0;i<next.size();i++) {String s = (String) next.get(i);
smtp = (s).substring(s.lastIndexOf(' ')+1);
break;
}
}
} catch (NamingException e) {e.printStackTrace();
}
return smtp;
}
}
正文完
发表至: java
2019-07-10