用Java寫的一個發郵件的東東(群發+多附件)[原創]

來源:互聯網
上載者:User

  2005.04.17發表於blog.csdn.net/zxub

  沒什麼好玩的了,最近看到好多地方有發郵件的東東,正好在看Java,就用Java寫了,需要下載mail.jar和activation.jar,此外,用到我前次寫的操作XML檔案的一個類(上篇文章),好了,不多說了,代碼貼貼,怎麼用就看自己了:

//JavaMail中一些我們需要的類
//1.Properties
//
//JavaMail需要Properties來建立一個session對象,其屬性值就是發送郵件的主機,如:
//
//Properties props = new Properties ();
//props.put("mail.smtp.host", "smtp.xxxx.com");//可以換上你的smtp主機名稱,就像你在OutLook中設定smtp主機名稱一樣。
//props.put("mail.smtp.auth", "true"); //通過驗證
//
//2.Session
//
//所有的基於JavaMail的程式都至少需要一個或全部的對話目標。
//
//Session session = Session.getInstance(props, null);
//
//3.MimeMessage
//
//資訊對象將把你所發送的郵件真實的反映出來。
//
//MimeMessage msg = new MimeMessage(session);
//
//4.Transport
//
//郵件的發送是由Transport來完成的:
//
//Transport.send(msg);

import java.awt.List;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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 org.dom4j.DocumentException;

/*
 * Created on 2005-4-14 21:27:16
 *
 */

/**
 * @author zxub
 * 
 */
public class MailSender {

 String host;
 String userName;
 String password;
 String from;
 String to;
 String subject;
 String body;

 String fileName;

 // 用於儲存發送附件的檔案名稱列表
 List arrFileName = new List();

 public MailSender(String to, String subject, String body)
   throws MalformedURLException, DocumentException {
  //初始化寄件者、收件者、主題等
  OperaXML OX = new OperaXML();
  this.from = OX.getNodeValue("config.xml", "config/Host1/From");
  this.host = OX.getNodeValue("config.xml", "config/Host1/SmtpHost");
  this.userName = OX.getNodeValue("config.xml", "config/Host1/UserName");
  this.password = OX.getNodeValue("config.xml", "config/Host1/Password");

  this.to = to;
  this.subject =subject;
  this.body = body;
 }

 // 用於收集附件名
 public void attachFile(String fileName) {
  this.arrFileName.add(fileName);
 }

 // 開始發送
 public boolean startSend() {

  //建立Properties對象
  Properties props = System.getProperties();
  //建立信件伺服器
  props.put("mail.smtp.host", this.host);
  props.put("mail.smtp.auth", "true"); //通過驗證
  //得到預設的對話對象
  Session session = Session.getDefaultInstance(props, null);
  try {
   //建立一個訊息,並初始化該訊息的各項元素
   MimeMessage msg = new MimeMessage(session);
   msg.setFrom(new InternetAddress(this.from));
   if (this.to.trim().length() > 0) {
    String[] arr = this.to.split(",");
    //int ReceiverCount=1;
    int receiverCount = arr.length;
    if (receiverCount > 0) {
     InternetAddress[] address = new InternetAddress[receiverCount];
     for (int i = 0; i < receiverCount; i++) {
      address[i] = new InternetAddress(arr[i]);
     }
     msg.addRecipients(Message.RecipientType.TO, address);
    } else {
     System.out
       .println("None receiver! The program will be exit!");
     System.exit(0);
    }
   } else {
    System.out.println("None receiver! The program will be exit!");
    System.exit(0);
   }
   msg.setSubject(subject);
   //後面的BodyPart將加入到此處建立的Multipart中
   Multipart mp = new MimeMultipart();      
   //擷取附件
   int FileCount = this.arrFileName.getItemCount();
   if (FileCount > 0) {
    for (int i = 0; i < FileCount; i++) {
     MimeBodyPart mbp = new MimeBodyPart();     
     //選擇出附件名
     fileName = arrFileName.getItem(i).toString();
     //得到資料來源
     FileDataSource fds = new FileDataSource(fileName);
     //得到附件本身並至入BodyPart
     mbp.setDataHandler(new DataHandler(fds));
     //得到檔案名稱同樣至入BodyPart
     mbp.setFileName(fds.getName());
     mp.addBodyPart(mbp);
    }
    MimeBodyPart mbp = new MimeBodyPart();
    mbp.setText(this.body);
    mp.addBodyPart(mbp);
    //移走集合中的所有元素
    arrFileName.removeAll();
    //Multipart加入到信件
    msg.setContent(mp);
   } else {
    //設定郵件內文
    msg.setText(this.body);
   }
   //設定信件頭的發送日期
   msg.setSentDate(new Date());
   msg.saveChanges();
   //發送信件
   Transport transport = session.getTransport("smtp");
   transport.connect(this.host, this.userName, this.password);
   transport.sendMessage(msg, msg
     .getRecipients(Message.RecipientType.TO));
   transport.close();
  } catch (MessagingException mex) {
   mex.printStackTrace();
   Exception ex = null;
   if ((ex = mex.getNextException()) != null) {
    ex.printStackTrace();
   }
   return false;
  }
  return true;
 }

 public static void main(String[] args) {

  try {
   MailSender sendmail = new MailSender("郵箱地址1,郵箱地址2",
     "郵件主題", "郵件內容");
   sendmail.attachFile("E:\\eclipse\\workspace\\MailSender\\MailSender.rar");//附件地址
   //sendmail.attachFile("附件2地址");....................
   sendmail.startSend();
   System.out.println("OK");
  } catch (Exception e) {
   e.printStackTrace();
  }

 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.