Java mail发送邮件

周五的工作中需要写个发邮件的程序,然后就学习了下,同时也在网上找了些别人写的代码学习了下,也看了看mail.jar的API

API比较好的介绍推荐个网址:http://blog.csdn.net/zapldy/article/details/3971579

直接上代码吧。


package com.mail;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMailUtil {

	private String sendAddress;
	private String receiveAddress;
	
	private String SMTPServer;
	private String username;
	private String password;
	private String subject;
	private String content;
	private ArrayList<String> file = new ArrayList<String>();//用于保存发送附件的文件名的集合 
	
	
	public SendMailUtil(String SMTPServer,String sendAddress,String receiveAddress,String username,
			String password,String subject,String content){
		this.sendAddress = sendAddress;
		this.SMTPServer = SMTPServer;
		this.subject = subject;
		this.content = content;
		this.receiveAddress = receiveAddress;
		this.username = username;
		this.password = password;
	}
	
	private static class Email_Autherticatorbean extends Authenticator {

		private String m_username = null;

		private String m_userpass = null;

		public Email_Autherticatorbean(String username, String userpass) {
			super();
			setUsername(username);
			setUserpass(userpass);
		}

		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(m_username, m_userpass);
		}

		public void setUsername(String username) {
			m_username = username;
		}

		public void setUserpass(String userpass) {
			m_userpass = userpass;
		}
	}
	
	public void sendMail(){
		Properties props = new Properties();
		props.put("mail.smtp.host", this.SMTPServer);
		props.put("mail.smtp.auth", "true");
		
		Session session = null;
		Email_Autherticatorbean SMTPAuth = new Email_Autherticatorbean(username,password);
		session = Session.getDefaultInstance(props,SMTPAuth);
		session.setDebug(true);
		
		Transport trans = null;
		try{
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(this.sendAddress));
			if (this.receiveAddress.indexOf(",") > 0)
				this.receiveAddress = this.receiveAddress.replaceAll(",", ",");
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.receiveAddress));
			msg.setSubject(subject);
			
			Multipart mp = new MimeMultipart();  
            MimeBodyPart mbp = new MimeBodyPart();  
            mbp.setContent("<meta http-equiv=Content-Type content=text/html; charset=GBK>"+
            					this.content, "text/html;charset=gb2312");  
            mp.addBodyPart(mbp);    
            if(!file.isEmpty()){//有附件  
            	String filename = "";
            	for(int i = 0 ; i < file.size() ; i ++){
            		 mbp=new MimeBodyPart();
            		 filename = file.get(i);
            		 FileDataSource fds=new FileDataSource(filename); //得到数据源  
            		 mbp.setDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart  
            		// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                   //  mbp.setFileName("=?GBK?B?"+enc.encode(filename.getBytes())+"?=");
            		 mbp.setFileName(MimeUtility.encodeText(filename));  //得到文件名同样至入BodyPart 
            		 mp.addBodyPart(mbp); 
            	}
            	file.clear();     
            }   
            msg.setContent(mp); //Multipart加入到信件  
            msg.setSentDate(new Date());     //设置信件头的发送日期  
            //发送信件  
            msg.saveChanges();   
            trans = session.getTransport("smtp");  
            trans.connect(SMTPServer, username, password);  
            trans.sendMessage(msg, msg.getAllRecipients());  
            trans.close();  
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void setSMTPServer(String SMTPServer){
		this.SMTPServer = SMTPServer;
	}
	
	/**设置发件人地址*/
	public void setSendAddress(String sendAddress){
		this.sendAddress = sendAddress;
	}
	
	public void setUsername(String username){
		this.username = username;
	}
	
	public void setPassword(String password){
		this.password = password;
	}
	
	/**设置收件人地址*/
	public void setReceiveAddress(String receiveAddress){
		this.receiveAddress = receiveAddress;
	}
	
	public void setSubject(String subject){
		this.subject = subject;
	}
	
	public void setContent(String content){
		this.content = content;
	}
	
	public void addAttachFile(String filename){
		this.file.add(filename);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String from = "******@163.com";
		String username = "******@163.com";
		String host = "smtp.163.com";
		String password = "******";
		String to = "******@qq.com,*******@gmail.com";//给多个邮箱同时发送
		String subject = "Java 发送的第一个邮件";
		String content = "Java Mail 已经发送邮件";
		SendMailUtil mail = new SendMailUtil(host,from,to,username,password,subject,content);
		//mail.addAttachFile("D:\\Test\\util\\SendMailUtil.java");
		mail.sendMail();
	}

}


发送邮件很简单,网上有很多详细的教程,建议多研究下API帮助更好的理解。

你可能感兴趣的:(java,exception,properties,session,String,email)