环境:jdk8,maven
需要的pom,高版本发送会验证spf,这个不会
现在发送邮件的FROM的域名必须和发送邮件的app在同一地址
<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;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。