发送电子邮件 1----javax.mail

javaMail发送电子邮件的方法,自己总结了个步骤:

1、首先需要获取发送邮件的Session对象

Session session = Session.getDefaultInstance(properties,authorcator);

2、根据session对象,获取待发送的邮件消息

MimeMessage mimeMessage = new MimeMessage(session);

3、设置发件人,收件人,标题,邮件内容,附件,发送时间等;

4、利用Transport发送邮件

 

以下是居然的实现代码:

1、邮件信息类:

package com.china.test.mail;

import java.util.Properties;

/**
 * 发送邮件需要使用的基本信息 
 * @author dove *
 */
public class MailSenderInfo {
	// 发送邮件的服务器的IP
    private String mailServerHost;    
    // 发送邮件的服务器的端口    
    private String mailServerPort = "25";    
    // 邮件发送者的地址    
    private String fromAddress;    
    // 邮件接收者的地址    
    private String[] toAddress;
    // 邮件密送接收者的地址
    private String[] toBlindCarbonCopyAddress;
    // 邮件抄送接收者的地址
    private String[] toCarbonCopyAddress;
    // 登陆邮件发送服务器的用户名
    private String userName;
    // 登陆邮件发送服务器的密码    
    private String password;    
    // 是否需要身份验证    
    private boolean validate = false;    
    // 邮件主题    
    private String subject;    
    // 邮件的文本内容    
    private String content;    
    // 邮件附件的文件名    
    private String[] attachFileNames;
    
	/**
	 * 获得邮件会话属性
	 */
	public Properties getProperties() {
		Properties pro = new Properties();
		pro.put("mail.smtp.host", this.mailServerHost);
		pro.put("mail.smtp.port", this.mailServerPort);
		pro.put("mail.smtp.auth", validate ? "true" : "false");
		return pro;
	}
    
	public String getMailServerHost() {
		return mailServerHost;
	}
	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}
	public String getMailServerPort() {
		return mailServerPort;
	}
	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}
	public String getFromAddress() {
		return fromAddress;
	}
	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}
	public String[] getToAddress() {
		return toAddress;
	}
	public void setToAddress(String[] toAddress) {
		this.toAddress = toAddress;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isValidate() {
		return validate;
	}
	public void setValidate(boolean validate) {
		this.validate = validate;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String[] getAttachFileNames() {
		return attachFileNames;
	}
	public void setAttachFileNames(String[] attachFileNames) {
		this.attachFileNames = attachFileNames;
	}

	public String[] getToBlindCarbonCopyAddress() {
		return toBlindCarbonCopyAddress;
	}

	public void setToBlindCarbonCopyAddress(String[] toBlindCarbonCopyAddress) {
		this.toBlindCarbonCopyAddress = toBlindCarbonCopyAddress;
	}

	public String[] getToCarbonCopyAddress() {
		return toCarbonCopyAddress;
	}

	public void setToCarbonCopyAddress(String[] toCarbonCopyAddress) {
		this.toCarbonCopyAddress = toCarbonCopyAddress;
	}
	
}

 

2、身份验证类

package com.china.test.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
 * 身份验证器
 * @author dove
 *
 */
public class MyAuthenticator extends Authenticator {
	private String username;
	private String password;
	public MyAuthenticator(){
		
	}
	
	public MyAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

 

3、发送邮件类

该类有两个功能,一个是发送普通文本邮件;一个是发送html邮件,两者的本质是相同的,mime类型有所区别而已,具体请看代码:

  1. package com.china.test.mail;   
  2.   
  3. import java.io.UnsupportedEncodingException;   
  4. import java.util.Date;   
  5. import java.util.Properties;   
  6.   
  7. import javax.activation.DataHandler;   
  8. import javax.activation.DataSource;   
  9. import javax.activation.FileDataSource;   
  10. import javax.mail.Address;   
  11. import javax.mail.BodyPart;   
  12. import javax.mail.Message;   
  13. import javax.mail.MessagingException;   
  14. import javax.mail.Multipart;   
  15. import javax.mail.Session;   
  16. import javax.mail.Transport;   
  17. import javax.mail.internet.AddressException;   
  18. import javax.mail.internet.InternetAddress;   
  19. import javax.mail.internet.MimeBodyPart;   
  20. import javax.mail.internet.MimeMessage;   
  21. import javax.mail.internet.MimeMultipart;   
  22. import javax.mail.internet.MimeUtility;   
  23.   
  24. /**  
  25.  * 简单邮件发送器  
  26.  * @author dove *  
  27.  */  
  28. public class SimpleMailSender {   
  29.     /**  
  30.      * 以文本格式发送邮件 (支持群发,带附件)  
  31.      * @param senderInfo 待发送的邮件的信息   
  32.      * @return  
  33.      */  
  34.     public static boolean sendMail(MailSenderInfo senderInfo){   
  35.         boolean flag = false;   
  36.            
  37.         // 判断是否需要身份验证   
  38.         MyAuthenticator authenticator = null;   
  39.         Properties props = senderInfo.getProperties();   
  40.         if(senderInfo.isValidate()){   
  41.             // 如果需要身份认证,则创建一个密码验证器      
  42.             authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());   
  43.         }   
  44.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session   
  45.         Session sendMailSession = Session.getDefaultInstance(props, authenticator);   
  46.            
  47.         try {   
  48.             // 根据session创建一个邮件消息   
  49.             Message sendMailMessage = new MimeMessage(sendMailSession);   
  50.             // 创建邮件发送者地址   
  51.             Address from = new InternetAddress(senderInfo.getFromAddress());   
  52.             // 设置邮件消息的发送者   
  53.             sendMailMessage.setFrom(from);   
  54.                
  55.             // 创建邮件接收者地址   
  56.             String[] tos = senderInfo.getToAddress();   
  57.             if(tos != null && tos.length != 0){   
  58.                 InternetAddress[] to = new InternetAddress[tos.length];   
  59.                 // 设置邮件消息的发送者   
  60.                 for (int i = 0; i < tos.length; i++) {   
  61.                     to[i] = new InternetAddress(tos[i]);   
  62.                 }   
  63.                 sendMailMessage.setRecipients(Message.RecipientType.TO, to);   
  64.             }   
  65.                
  66.             // 设置邮件抄送者地址   
  67.             String[] toCCs = senderInfo.getToCarbonCopyAddress();   
  68.             if(toCCs != null && toCCs.length != 0){   
  69.                 InternetAddress[] toCC = new InternetAddress[toCCs.length];   
  70.                 // 设置邮件消息的发送者   
  71.                 for (int i = 0; i < toCCs.length; i++) {   
  72.                     toCC[i] = new InternetAddress(toCCs[i]);   
  73.                 }   
  74.                 sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);   
  75.             }   
  76.                
  77.             // 设置邮件密送者地址   
  78.             String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();   
  79.             if(toBCCs != null && toBCCs.length != 0){   
  80.                 InternetAddress[] toBCC = new InternetAddress[toBCCs.length];   
  81.                 for (int i = 0; i < toBCCs.length; i++) {   
  82.                     toBCC[i] = new InternetAddress(toBCCs[i]);   
  83.                 }   
  84.                 sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);   
  85.             }   
  86.                
  87.             // 设置邮件主题   
  88.             sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));   
  89.             // 设置邮件内容   
  90.             //sendMailMessage.setText(senderInfo.getContent());   
  91.             Multipart multipart = new MimeMultipart();   
  92.             // 邮件文本内容   
  93.             if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){   
  94.                 BodyPart part = new MimeBodyPart();   
  95.                 part.setContent(senderInfo.getContent(), "text/plain;charset=utf-8");//设置邮件文本内容   
  96.                 multipart.addBodyPart(part);   
  97.             }   
  98.                
  99.             // 附件   
  100.             String attachFileNames[] = senderInfo.getAttachFileNames();   
  101.             int leng = attachFileNames == null ? 0 : attachFileNames.length;   
  102.             for (int i = 0; i < leng; i++) {   
  103.                 BodyPart part = new MimeBodyPart();   
  104.                 // 根据文件名获取数据源   
  105.                 DataSource dataSource = new FileDataSource(attachFileNames[i]);   
  106.                 DataHandler dataHandler = new DataHandler(dataSource);   
  107.                 // 得到附件本身并至入BodyPart   
  108.                 part.setDataHandler(dataHandler);   
  109.                 // 得到文件名同样至入BodyPart   
  110.                 part.setFileName(MimeUtility.encodeText(dataSource.getName()));   
  111.                 multipart.addBodyPart(part);   
  112.             }   
  113.                
  114.             sendMailMessage.setContent(multipart);   
  115.             // 设置邮件发送的时间   
  116.             sendMailMessage.setSentDate(new Date());   
  117.             // 发送邮件   
  118.             //Transport.send(sendMailMessage);   
  119.             Transport transport = sendMailSession.getTransport("smtp");   
  120.             transport.connect(senderInfo.getUserName(), senderInfo.getPassword());   
  121.             transport.send(sendMailMessage,sendMailMessage.getAllRecipients());   
  122.             transport.close();   
  123.                
  124.             flag = true;   
  125.         } catch (AddressException e) {   
  126.             e.printStackTrace();   
  127.         } catch (MessagingException e) {   
  128.             e.printStackTrace();   
  129.         } catch (UnsupportedEncodingException e) {   
  130.             e.printStackTrace();   
  131.         }   
  132.            
  133.         return flag;   
  134.     }   
  135.        
  136.     public static boolean sendHtmlMail(MailSenderInfo senderInfo){   
  137.         boolean flag = false;   
  138.            
  139.         // 判断是否需要身份验证   
  140.         MyAuthenticator authenticator = null;   
  141.         Properties props = senderInfo.getProperties();   
  142.         if(senderInfo.isValidate()){   
  143.             // 如果需要身份认证,则创建一个密码验证器      
  144.             authenticator = new MyAuthenticator(senderInfo.getUserName(), senderInfo.getPassword());   
  145.         }   
  146.         // 根据邮件会话属性和密码验证器构造一个发送邮件的session   
  147.         Session sendMailSession = Session.getDefaultInstance(props, authenticator);   
  148.            
  149.         try {   
  150.             // 根据session创建一个邮件消息   
  151.             Message sendMailMessage = new MimeMessage(sendMailSession);   
  152.             // 创建邮件发送者地址   
  153.             Address from = new InternetAddress(senderInfo.getFromAddress());   
  154.             // 设置邮件消息的发送者   
  155.             sendMailMessage.setFrom(from);   
  156.                
  157.             // 创建邮件接收者地址   
  158.             String[] tos = senderInfo.getToAddress();   
  159.             if(tos != null && tos.length != 0){   
  160.                 InternetAddress[] to = new InternetAddress[tos.length];   
  161.                 // 设置邮件消息的发送者   
  162.                 for (int i = 0; i < tos.length; i++) {   
  163.                     to[i] = new InternetAddress(tos[i]);   
  164.                 }   
  165.                 sendMailMessage.setRecipients(Message.RecipientType.TO, to);   
  166.             }   
  167.                
  168.             // 设置邮件抄送者地址   
  169.             String[] toCCs = senderInfo.getToCarbonCopyAddress();   
  170.             if(toCCs != null && toCCs.length != 0){   
  171.                 InternetAddress[] toCC = new InternetAddress[toCCs.length];   
  172.                 // 设置邮件消息的发送者   
  173.                 for (int i = 0; i < toCCs.length; i++) {   
  174.                     toCC[i] = new InternetAddress(toCCs[i]);   
  175.                 }   
  176.                 sendMailMessage.addRecipients(Message.RecipientType.CC, toCC);   
  177.             }   
  178.                
  179.             // 设置邮件密送者地址   
  180.             String[] toBCCs = senderInfo.getToBlindCarbonCopyAddress();   
  181.             if(toBCCs != null && toBCCs.length != 0){   
  182.                 InternetAddress[] toBCC = new InternetAddress[toBCCs.length];   
  183.                 for (int i = 0; i < toBCCs.length; i++) {   
  184.                     toBCC[i] = new InternetAddress(toBCCs[i]);   
  185.                 }   
  186.                 sendMailMessage.addRecipients(Message.RecipientType.BCC, toBCC);   
  187.             }   
  188.                
  189.             // 设置邮件主题   
  190.             sendMailMessage.setSubject(MimeUtility.encodeText(senderInfo.getSubject(),"utf-8","B"));   
  191.             // 设置邮件内容   
  192.             //sendMailMessage.setText(senderInfo.getContent());   
  193.             Multipart multipart = new MimeMultipart();   
  194.             // 邮件文本内容   
  195.             if(senderInfo.getContent() != null && !"".equals(senderInfo.getContent())){   
  196.                 BodyPart part = new MimeBodyPart();   
  197.                 part.setContent(senderInfo.getContent(), "text/html;charset=utf-8");//设置邮件文本内容   
  198.                 multipart.addBodyPart(part);   
  199.             }   
  200.                
  201.             // 附件   
  202.             String attachFileNames[] = senderInfo.getAttachFileNames();   
  203.             int leng = attachFileNames == null ? 0 : attachFileNames.length;   
  204.             for (int i = 0; i < leng; i++) {   
  205.                 BodyPart part = new MimeBodyPart();   
  206.                 // 根据文件名获取数据源   
  207.                 DataSource dataSource = new FileDataSource(attachFileNames[i]);   
  208.                 DataHandler dataHandler = new DataHandler(dataSource);   
  209.                 // 得到附件本身并至入BodyPart   
  210.                 part.setDataHandler(dataHandler);   
  211.                 // 得到文件名同样至入BodyPart   
  212.                 part.setFileName(MimeUtility.encodeText(dataSource.getName()));   
  213.                 multipart.addBodyPart(part);   
  214.             }   
  215.                
  216.             sendMailMessage.setContent(multipart);   
  217.             // 设置邮件发送的时间   
  218.             sendMailMessage.setSentDate(new Date());   
  219.             // 发送邮件   
  220.             //Transport.send(sendMailMessage);   
  221.             Transport transport = sendMailSession.getTransport("smtp");   
  222.             transport.connect(senderInfo.getUserName(), senderInfo.getPassword());   
  223.             transport.send(sendMailMessage,sendMailMessage.getAllRecipients());   
  224.                
  225.             // 关闭transport   
  226.             transport.close();   
  227.                
  228.             flag = true;   
  229.         } catch (AddressException e) {   
  230.             e.printStackTrace();   
  231.         } catch (MessagingException e) {   
  232.             e.printStackTrace();   
  233.         } catch (UnsupportedEncodingException e) {   
  234.             e.printStackTrace();   
  235.         }   
  236.            
  237.         return flag;   
  238.     }   
  239.        
  240.     public static void main(String[] args) {   
  241.         MailSenderInfo mailInfo = new MailSenderInfo();   
  242.         mailInfo.setMailServerHost("smtp.sina.com");   
  243.         mailInfo.setMailServerPort("25");   
  244.         mailInfo.setValidate(true);   
  245.         mailInfo.setUserName("********@sina.com");   
  246.         mailInfo.setPassword("*********");// 您的邮箱密码   
  247.         mailInfo.setFromAddress("[email protected]");   
  248.         String[] to = {"********@bj.china.com"};   
  249.         mailInfo.setToAddress(to);   
  250.         String[] toCC = {"**********@qq.com"};   
  251.         mailInfo.setToCarbonCopyAddress(toCC);   
  252.         String[] toBCC = {"*******@sina.com"};   
  253.         mailInfo.setToBlindCarbonCopyAddress(toBCC);   
  254.         mailInfo.setAttachFileNames(new String[]{"C:/Documents and Settings/Administrator/桌面/考勤休假制度表格(新).xls","C:/Documents and Settings/Administrator/桌面/dove.jpg"});   
  255.         mailInfo.setSubject("发送HTML邮件");   
  256.         String body = "<table width=\"80%\" border=\"1\" cellpadding=\"0\" cellspacing=\"0\" style=\"align:center;text-align:center\"><tr><td>你好</td><td>你好</td><td>你好</td></tr></table>";   
  257.         mailInfo.setContent(body);   
  258.         // 这个类主要来发送邮件   
  259.         System.out.println(SimpleMailSender.sendHtmlMail(mailInfo));;//发送文体格式   
  260.     }   

你可能感兴趣的:(java)