commons-mail+javaMail 实现java的邮件发送功能

1、需要的包为:commons-email-1.2.jar;activation.jar;mail.jar,其中这三个包的下载地址为: http://download.csdn.net/source/3440071。

package com.stone.mail;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

public class MailDemo {
 public static void main(String[] args) {

  // 目的地集合
  Collection<String> sendTo = new ArrayList<String>();
  sendTo.add("[email protected]");
  sendTo.add("[email protected]");
  // 添加2个附件
  EmailAttachment attachment1 = new EmailAttachment();
  attachment1.setPath("C:/Users/Public/Pictures/capture/extra1.png");
  attachment1.setName("extra1.png");
  attachment1.setDisposition(EmailAttachment.ATTACHMENT);

  EmailAttachment attachment2 = new EmailAttachment();
  attachment2.setPath("C:/Users/Public/Pictures/capture/extra2.png");
  attachment2.setName("extra2.png");
  attachment2.setDisposition(EmailAttachment.ATTACHMENT);

  // Create email message
  try {
   HtmlEmail email = new HtmlEmail();
   email.setHostName("smtp.foxmail.com");
   email.setSubject("test Mail");
   email.setCharset("GB2312");
   email.setAuthentication("[email protected]", "!@#$%^&*");
   email.setFrom("[email protected]");
   //设置收件人
   for (String receiver : sendTo) {
    email.addTo(receiver);
   }
   email.setHtmlMsg("<html><body><font size='5' color='red'>This is a 测试信 from [email protected].</font></body></html>");
   email.attach(attachment1);
   email.attach(attachment2);
   // send email
   email.send();
  } catch (EmailException e) {
   e.printStackTrace();
  }
  System.out.println("郵件已經成功發送");
 }
}

你可能感兴趣的:(java,String,测试,Class,email,javamail)