javamail發送郵件(親測可用)

package com.ncxdkj.web.communication;

import java.io.IOException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMail {
	private MimeMessage mimeMsg; // MIME郵件對象
	private Session session; // 郵件會話對象
	private Properties props; // 系統屬性
	private Multipart mp; // Multipart對象,郵件內容,標題,附件等內容均添加到其中後再生成MimeMessage對象
	
	public static void main(String[] args) throws Exception{  
	    String smtp = "smtp.qq.com";  
	    String from = "xxxxxx@qq.com";  
	    String to = "xxxxxx@qq.com";
	    String to1 = "xxxxxx@163.com";
	    //String copyto = "sherlock_001@163.com";  
	    String subject = "測試";  
	    String content = "郵件內容";  
	    String username="xxxxxx@qq.com";  
	    String password=""; //受權碼
	    String filename = "C:\\Users\\Administrator\\Desktop\\content.jsp";  
	    
	    SendMail.send(smtp,25, from, new String[]{to,to1}, subject, content, username, password, new String[]{filename});
	}
	/**
	 * Constructor
	 * 
	 * @param smtp
	 *            郵件發送服務器
	 */
	public SendMail(String smtp,Integer smtpPort,Authenticator a) {
		setSmtpHost(smtp,smtpPort);
		createMimeMessage(a);
	}

	/**
	 * 設置郵件發送服務器
	 * 
	 * @param hostName
	 *            String
	 */
	public void setSmtpHost(String hostName,Integer smtpPort) {
		System.out.println("設置系統屬性:mail.smtp.host = " + hostName);
		if (props == null)
			props = new Properties(); // 得到系統屬性對象
		props.put("mail.smtp.host", hostName); // 設置SMTP主機
		props.put("mail.smtp.port", smtpPort); // 設置SMTP主機端口
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable","true");  //qq郵箱須要加這句否則會報錯
	}

	/**
	 * 建立MIME郵件對象
	 * 
	 * @return
	 */
	public boolean createMimeMessage(Authenticator a) {
		try {
			System.out.println("準備獲取郵件會話對象!");
			session = Session.getInstance(props, a); // 得到郵件會話對象
		} catch (Exception e) {
			System.err.println("獲取郵件會話對象時發生錯誤!" + e);
			return false;
		}

		System.out.println("準備建立MIME郵件對象!");
		try {
			mimeMsg = new MimeMessage(session); // 建立MIME郵件對象
			mp = new MimeMultipart();

			return true;
		} catch (Exception e) {
			System.err.println("建立MIME郵件對象失敗!" + e);
			return false;
		}
	}
	/**
	 * 設置郵件主題
	 * 
	 * @param mailSubject
	 * @return
	 */
	public boolean setSubject(String mailSubject) {
		System.out.println("設置郵件主題!");
		try {
			mimeMsg.setSubject(mailSubject);
			return true;
		} catch (Exception e) {
			System.err.println("設置郵件主題發生錯誤!");
			return false;
		}
	}

	/**
	 * 設置郵件正文
	 * 
	 * @param mailBody
	 *            String
	 */
	public boolean setBody(String mailBody) {
		try {
			BodyPart bp = new MimeBodyPart();
			bp.setContent("" + mailBody, "text/html;charset=GBK");
			mp.addBodyPart(bp);
			mimeMsg.setContent(mp);
			return true;
		} catch (Exception e) {
			System.err.println("設置郵件正文時發生錯誤!" + e);
			return false;
		}
	}

	/**
	 * 添加附件
	 * 
	 * @param filename
	 *            String
	 */
	public boolean addFileAffix(String filename) {

		System.out.println("增長郵件附件:" + filename);
		try {
			BodyPart bp = new MimeBodyPart();
			FileDataSource fileds = new FileDataSource(filename);
			bp.setDataHandler(new DataHandler(fileds));
			bp.setFileName(fileds.getName());
			mp.addBodyPart(bp);
			return true;
		} catch (Exception e) {
			System.err.println("增長郵件附件:" + filename + "發生錯誤!" + e);
			return false;
		}
	}

	/**
	 * 設置發信人
	 * 
	 * @param from
	 *            String
	 */
	public boolean setFrom(String from) {
		System.out.println("設置發信人!");
		try {
			mimeMsg.setFrom(new InternetAddress(from)); // 設置發信人
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 設置收信人
	 * 
	 * @param to
	 *            String
	 */
	public boolean setTo(String to) {
		if (to == null)
			return false;
		try {
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/**
	 * 設置多個收信人
	 * */
	public boolean setMoreTo(String []toArray){
		if (toArray == null||toArray.length<=0)
			return false;
		try {
			int num = toArray.length;  
			InternetAddress[] addresses = new InternetAddress[num];  
			for (int i = 0; i <num; i++) {  
				addresses[i] = new InternetAddress(toArray[i]);
			}
			mimeMsg.setRecipients(Message.RecipientType.TO,addresses);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/**
	 * 設置抄送人
	 * 
	 * @param copyto
	 *            String
	 */
	public boolean setCopyTo(String copyto) {
		if (copyto == null)
			return true;
		try {
			mimeMsg.setRecipients(Message.RecipientType.CC,
					(Address[]) InternetAddress.parse(copyto));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 發送郵件
	 */
	public boolean sendOut() {
		try {
			System.out.println("正在發送郵件....");
			Transport.send(mimeMsg);
			System.out.println("發送郵件成功!");
			return true;
		} catch (Exception e) {
			System.err.println("郵件發送失敗!" );
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 調用sendOut方法完成郵件發送
	 * 
	 * @param smtp
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @param username
	 * @param password
	 * @return boolean
	 */
	public static boolean send(String smtp,Integer smtpPort,String from,  String[] to,
			String subject, String content, String username, String password) {
		Authenticator authenticator = new Email_Authenticator(from, password);
		SendMail theMail=new SendMail(smtp,smtpPort,authenticator);
		if (!theMail.setSubject(subject))
			return false;
		if (!theMail.setBody(content))
			return false;
		if (!theMail.setMoreTo(to))
			return false;
		if (!theMail.setFrom(from))
			return false;
		if (!theMail.sendOut())
			return false;
		return true;
	}

	/**
	 * 調用sendOut方法完成郵件發送,帶抄送
	 * 
	 * @param smtp
	 * @param from
	 * @param to
	 * @param copyto
	 * @param subject
	 * @param content
	 * @param username
	 * @param password
	 * @return boolean
	 */
	public static boolean sendAndCc(String smtp,Integer smtpPort, String from, String to,
			String copyto, String subject, String content, String username,
			String password) {
		Authenticator authenticator = new Email_Authenticator(from, password);
		SendMail theMail=new SendMail(smtp,smtpPort,authenticator);

		if (!theMail.setSubject(subject))
			return false;
		if (!theMail.setBody(content))
			return false;
		if (!theMail.setTo(to))
			return false;
		if (!theMail.setCopyTo(copyto))
			return false;
		if (!theMail.setFrom(from))
			return false;
		if (!theMail.sendOut())
			return false;
		return true;
	}

	/**
	 * 調用sendOut方法完成郵件發送,帶附件
	 * 
	 * @param smtp
	 * @param from
	 * @param to
	 * @param subject
	 * @param content
	 * @param username
	 * @param password
	 * @param filename
	 *            附件路徑
	 * @return
	 */
	public static boolean send(String smtp,Integer smtpPort, String from, String to[],
			String subject, String content, String username, String password,
			String filename[])  throws IOException, AddressException,MessagingException{
		Authenticator authenticator = new Email_Authenticator(from, password);
		SendMail sendEmail=new SendMail(smtp,smtpPort,authenticator);
		if (!sendEmail.setMoreTo(to))
			return false;
		if (!sendEmail.setFrom(from))
			return false;
		if (!sendEmail.setSubject(subject))
			return false;
		if(filename!=null){
			for(String s:filename){
				if (!sendEmail.addFileAffix(s))
					return false;
			}
		}
		if (!sendEmail.setBody(content))
			return false;
		if (!sendEmail.sendOut())
			return false;
		return true;
	}

	/**
	 * 調用sendOut方法完成郵件發送,帶附件和抄送
	 * 
	 * @param smtp
	 * @param from
	 * @param to
	 * @param copyto
	 * @param subject
	 * @param content
	 * @param username
	 * @param password
	 * @param filename
	 * @return
	 */
	public static boolean sendAndCc(String smtp,Integer smtpPort, String from, String[] to,
			String copyto, String subject, String content, String username,
			String password, String filename[]) throws Exception{
		Authenticator authenticator = new Email_Authenticator(from, password);
		SendMail theMail=new SendMail(smtp,smtpPort,authenticator);
		if (!theMail.setSubject(subject))
			return false;
		if (!theMail.setBody(content))
			return false;
		if(filename!=null){
			for(String s:filename){
				//s=new String(s.getBytes(),"UTF-8");
				if (!theMail.addFileAffix(s))
					return false;
			}
		}
		if (!theMail.setMoreTo(to))
			return false;
		if (!theMail.setCopyTo(copyto))
			return false;
		if (!theMail.setFrom(from))
			return false;
		if (!theMail.sendOut())
			return false;
		return true;
	}
}
相關文章
相關標籤/搜索