JavaMail发送邮件(普通邮件,html邮件以及附件邮件)

实现普通邮件,html邮件以及附件邮件的发送;此例子使用的是163邮箱

邮箱的服务地址,邮件用户名密码在配置文件中读取;

#邮箱地址
mailAddress=
#邮箱服务
mailServer=smtp.163.com
#邮箱服务
mailHost=imap.163.com
#邮件用户名
mailAccount=
#邮箱密码
mailPassword=

发送邮件类:

public class SendEmail {
 
 private static String mailAddress;
 private static String mailServer;
 private static String mailAccount;
 static {
  mailAddress = WorkflowUitl.getWorkflowPropertys("mailAddress");
  mailServer = WorkflowUitl.getWorkflowPropertys("mailServer");
  mailAccount = WorkflowUitl.getWorkflowPropertys("mailAccount");
 }
 /**
  * 发送普通邮件
  * 
  * @throws Exception
  */
 public static void sendNormalMail(Email email) throws Exception {

  Properties prop = new Properties(); // 获取系统环境
  Authenticator auth = new MailAuthenticator(); // 邮件服务器认证
  prop.put("mail.smtp.host", mailServer);
  prop.put("mail.smtp.auth", "true");
  Session session = Session.getDefaultInstance(prop, auth);// 设置对话和邮件服务器进行通讯

  Message message = new MimeMessage(session);
  /*
   * 设置邮件对象
   */
  try {
   message.setSubject(email.getEmail_subject()); // 设置邮件主题
   message.setContent(email.getEmail_content(), "text/plain"); // 设置邮件格式
   message.setHeader("Header:", email.getEmail_header()); // 设置邮件标题
   message.setSentDate(new Date()); // 设置发送时间
   Address address = new InternetAddress(mailAddress,mailAccount); // 设置发信人地址
   message.setFrom(address);
   // 设置接收人地址
   // 设置多个收件人地址
   List list = new ArrayList();// 不能使用string类型的类型,这样只能发送一个收件人
   for (int i = 0; i < email.getEmail_to().length; i++) {
    list.add(new InternetAddress(email.getEmail_to()[i]));
   }
   InternetAddress[] internetAddressTo = (InternetAddress[]) list
     .toArray(new InternetAddress[list.size()]);
   message.setRecipients(Message.RecipientType.TO, internetAddressTo);

   message.saveChanges();
   System.out.println("开始发送邮件……");
   Transport.send(message); // 发送邮件
   System.out.println("发送成功!");

  } catch (MessagingException e) {
   System.out.println("发送失败!");
   e.printStackTrace();
  }

 }

 /**
  * 发送带附件的邮件
  * 
  * @throws UnsupportedEncodingException
  */
 public static boolean sendEmailWithAttachment(Email email)
   throws UnsupportedEncodingException {
  Properties prop = new Properties();
  prop.put("mail.smtp.host", mailServer);
  prop.put("mail.smtp.auth", "true");
  Authenticator auth = new MailAuthenticator();
  Session session = Session.getDefaultInstance(prop, auth);
  

Message message = new MimeMessage(session);   boolean flag = false;   try {    message.setSubject(email.getEmail_subject());// 设置邮件主题    message.setHeader("Header:", email.getEmail_header()); // 设置邮件标题    message.setSentDate(new Date()); // 设置发送时间    Address addressFrom = new InternetAddress(mailAddress, mailAccount); // 设置发信人地址    message.setFrom(addressFrom);    BodyPart messageBodyPart = new MimeBodyPart();    messageBodyPart.setContent(email.getEmail_content(),  "text/html;charset=utf-8");    Multipart multipart = new MimeMultipart();    multipart.addBodyPart(messageBodyPart);    MimeBodyPart mimeBodyPart;    //多个附件    for (int i = 0; i < email.getEmail_file().size(); i++) {     Map map = email.getEmail_file().get(i);     String fileSource="";     String fileName="";     for (String key : map.keySet()) {      fileSource = key;      fileName = map.get(key);        }     mimeBodyPart = new MimeBodyPart();     DataSource source = new FileDataSource(fileSource);     mimeBodyPart.setDataHandler(new DataHandler(source));     mimeBodyPart.setFileName(MimeUtility.encodeText(fileName));     multipart.addBodyPart(mimeBodyPart);// Put parts in    }    message.setContent(multipart);        // 设置多个收件人地址    List list = new ArrayList();// 不能使用string类型的类型,这样只能发送一个收件人    for (int i = 0; i < email.getEmail_to().length; i++) {     list.add(new InternetAddress(email.getEmail_to()[i]));    }    InternetAddress[] internetAddressTo = (InternetAddress[]) list      .toArray(new InternetAddress[list.size()]);    message.setRecipients(Message.RecipientType.TO, internetAddressTo);

   message.saveChanges();    System.out.println("开始发送邮件……");

   Transport.send(message);

System.out.println("发送成功!"); flag = true; } catch (MessagingException e) { System.out.println("发送失败!"); flag = false; e.printStackTrace(); } return flag; } /** * 发送带html的邮件 * * @throws UnsupportedEncodingException */ public static void sendEmailWithHtml(Email email) throws UnsupportedEncodingException { Properties prop = new Properties(); Authenticator auth = new MailAuthenticator(); prop.put("mail.smtp.host", mailServer); prop.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(prop, auth); Message message = new MimeMessage(session); String htmlText = email.getEmail_content(); try { message.setSubject(email.getEmail_subject()); message.setContent(htmlText,"text/html;charset=utf-8"); message.setSentDate(new Date()); Address address = new InternetAddress(mailAddress, mailAccount); // 设置多个收件人地址 List list = new ArrayList();// 不能使用string类型的类型,这样只能发送一个收件人 for (int i = 0; i < email.getEmail_to().length; i++) { list.add(new InternetAddress(email.getEmail_to()[i])); } InternetAddress[] internetAddressTo = (InternetAddress[]) list .toArray(new InternetAddress[list.size()]); message.setRecipients(Message.RecipientType.TO, internetAddressTo); message.setFrom(address); message.saveChanges(); System.out.println("开始发送邮件……"); Transport.send(message); System.out.println("发送成功!"); } catch (MessagingException e) { System.out.println("发送失败!"); e.printStackTrace(); } } /** * 测试 * * @param args */ public static void main(String args[]) { Email email = new Email(); email.setEmail_header("header"); email.setEmail_subject("测试邮件发送"); email.setEmail_content("sssssssssssssssssssssssssssssss"); String[] to = { "[email protected]", "[email protected]" }; email.setEmail_to(to); try { // 发送普通邮件 sendNormalMail(email); // 发送带html的邮件 sendEmailWithHtml(email); email.setEmail_file("C:/Users/SF/Pictures/11.jpg"); // 发送带附件的邮件 sendEmailWithAttachment(email); } catch (Exception e) { e.printStackTrace(); } } }



 

邮箱用户名密码类:

 

package cn.jasgroup.jasframework.utils.mailutil;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

import cn.jasgroup.jasframework.workflow.utils.WorkflowUitl;

public class MailAuthenticator extends Authenticator {
	private final static String mailAddress; 
	private final static String mailPassword; 

	static {
		mailAddress = WorkflowUitl.getWorkflowPropertys("mailAddress");
		mailPassword = WorkflowUitl.getWorkflowPropertys("mailPassword");
	}
	protected PasswordAuthentication getPasswordAuthentication(){ 
		return new PasswordAuthentication(mailAddress,mailPassword); 
	}
}

邮件实体类:

 
  

package cn.jasgroup.jasframework.utils.mailutil;

import java.util.Date;

public class Email {  public Date sendDate=null;

 private String[] email_to;//收件人地址  private String email_subject;//邮件主题  private String email_header;//邮件标题  private String email_content;//邮件内容  private String email_file;//发送附件邮件时的附件地址  public Email(){}    public String getEmail_content() {   return email_content;  }  public void setEmail_content(String email_content) {   this.email_content = email_content;  }  public String getEmail_subject() {   return email_subject;  }  public void setEmail_subject(String emailSubject) {   email_subject = emailSubject;  }  public String[] getEmail_to() {   return email_to;  }  public void setEmail_to(String[] email_to) {   this.email_to = email_to;  }  public String getEmail_header() {   return email_header;  }  public void setEmail_header(String emailHeader) {   email_header = emailHeader;  }  public String getEmail_file() {   return email_file;  }  public void setEmail_file(String emailFile) {   email_file = emailFile;  }

  }



 


 

 

 

 

 

 

 

你可能感兴趣的:(JavaMail,java)