package com.liu.test; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Hashtable; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; public class SendMail { public static void main(String[] args) throws NamingException, MessagingException { // DNS服务器,看看本机的DNS配置 MailMessage mailMessage = new MailMessage(); mailMessage.setSubject("测试"); mailMessage.setFrom("有效的邮箱域名"); //像大型的邮箱不可以发例如qq、163; String fileNames[] ={}; mailMessage.setFileNames(fileNames); String tos[] = {"xxxxxxx@qq.com"}; mailMessage.setTos(tos); mailMessage.setContent("工资加倍"); try { sendMail(mailMessage); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void sendMail(MailMessage mailMessage) throws Exception{ // DNS服务器,如果需要的话手工设置一下。 String dns = "dns://"; //得到接受方的服务器域名 //先从邮件中封装的收件人地址里取出收件人所在发服务器地址,然后通过该地址查找本地DNS记录 String sendUser = mailMessage.getTos()[0]; String domain = sendUser.substring(sendUser.indexOf('@') + 1); Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); env.put(Context.PROVIDER_URL, dns); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(domain, new String[] {"MX"}); if (attrs == null || attrs.size() <= 0) { throw new java.lang.IllegalStateException( "Error: Your DNS server has no Mail eXchange records!"); } NamingEnumeration servers = attrs.getAll(); // 列出所有邮件服务器: String smtpHost = null; boolean isSend = false; StringBuffer buf = new StringBuffer(); while (servers.hasMore()) { Attribute hosts = (Attribute) servers.next(); for (int i = 0; i < hosts.size(); ++i) { //sample: 20 mx2.qq.com smtpHost = (String) hosts.get(i); //parse the string to get smtpHost. sample: mx2.qq.com smtpHost = smtpHost.substring(smtpHost.lastIndexOf(' ') + 1); smtpHost = smtpHost.replace("com.", "com"); try { sendEms(smtpHost,mailMessage); isSend = true; return; } catch (Exception e) { buf.append(e.toString()).append(" "); continue; } } } } private static boolean sendEms(String smtpHost, MailMessage mailMessage) throws MessagingException, GeneralSecurityException{ Properties p = new Properties(); p.put("mail.smtp.host", smtpHost); p.put("mail.smtp.port", "25"); p.put("mail.smtp.auth", "false"); p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getInstance(p); session.setDebug(true); MimeMessage msg = new MimeMessage(session); // 加载发件人地址 String sendUser = mailMessage.getFrom(); if(sendUser==null || sendUser.trim().isEmpty()){ return false; } msg.setFrom(new InternetAddress(sendUser));//可发匿名信 // 加载收件人地址 String[] receipters =mailMessage.getTos(); if (receipters == null || receipters.length == 0) { return false; } // 加载标题 String subject =mailMessage.getSubject(); InternetAddress internetAddress[] = new InternetAddress[receipters.length]; for (int i = 0; i < internetAddress.length; i++) { internetAddress[i] = new InternetAddress(receipters[i]); } msg.addRecipients(Message.RecipientType.TO, internetAddress); msg.setSubject(subject); msg.setHeader("X-Mailer", "JavaMail"); msg.setSentDate(new Date()); Multipart mimeMultipart = new MimeMultipart(); //内容部分. BodyPart contentBodyPart = new MimeBodyPart(); //add email content part. // 设置邮件的文本内容 contentBodyPart.setContent(mailMessage.getContent(), "text/html;charset=UTF-8"); mimeMultipart.addBodyPart(contentBodyPart); msg.setContent(mimeMultipart); msg.setSentDate(new Date()); msg.saveChanges(); Transport transport=session.getTransport("smtp"); transport.connect(); transport.send(msg, msg.getAllRecipients()); transport.close(); System.out.println("Send html email success.");; return true; } }