環境:jdk8,maven
須要的pom,高版本發送會驗證spf,這個不會
如今發送郵件的FROM的域名必須和發送郵件的app在同一地址java
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.6</version> </dependency>
純文本郵件內容發送api
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; } }