JAvax.mail java送信メールの実装

10130 ワード

以下に完全に実行できるコードがあります.本人が直接テストして、運行できます.添付ファイルに使用するjarパッケージとソースコード.必要な友达は直接ダウンロードしてテストと研究を行うことができて、本人もネット上で見つけたコードです.分かち合う
ダイレクトソース
1.メールの基本情報(便宜上、そのまま静的に設定)
次はjavabeanにしたほうがいいです.

package com.lgf.Email;

import java.util.Date;

public class EmailMessage 
{
	/**
	 *      ,        。
	 *              
	 */
	
//	     
	public  static String TO = "[email protected]";   
//	     
	public  static String FROM = "[email protected]";  
	public  static String FROM_NAME = "xxx"; 
//	    	
	public  static String CC="[email protected]";   	
//	    
	public  static String BCC="[email protected]";   	
//	     
	public 	static String Email_Content = "text/plain";
//	    
	public  static String Email_Subject = "Test Email With JavaMail";   
//	   
	public  static String Email_Header = "This Is Email Header";   	
//	  
	public  static String Email_Body = "<a href=\"http://www.baidu.com\">This Is Email Body</a>"; 
//	   	  QQ      smtp.qq.com
	public  static String Email_Host = "smtp.xxx.com";   		
//	    
	public 	static Date sendDate = new Date(); 	
//	            
	public 	static boolean validate = true; 	
}



2.サーバ認証(通常ログイン時のユーザー名とパスワード)

package com.lgf.Email;

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

/**
 *          
 * @author lgf
 *
 */
public class MailAuthenticator extends Authenticator{
	private  String username="xxxxx";   
	private  String password="xxxxx";   
	
	public MailAuthenticator() {
		super();
	}
	
	/**
	 *            
	 */
	public MailAuthenticator(String userName , String password) {
		super();
		this.username = userName;
		this.password = password;
	}
	protected PasswordAuthentication getPasswordAuthentication()
	{   
		return new PasswordAuthentication(this.username,this.password);   
	}   
}



[size=large]
3.メール送信前の設定情報と手順

package com.lgf.Email;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
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 com.lgf.SendEmail.MailAuthenticator;

public class SendEmail 
{
	
	/**  
	*         
	* @throws Exception  
	*/   
	public void doSendNormalMail() 
	{   
//		         
		Properties prop = new Properties();  
		Authenticator auth = null;
//		            
		if (EmailMessage.validate) 
		{
//			                 
			auth =	new MailAuthenticator();  
		}
//		       
		prop.put("mail.smtp.host", EmailMessage.Email_Host);   
		prop.put("mail.smtp.auth", "true");   
		
//		               
		Session session = Session.getDefaultInstance(prop, auth);   
//		      Debug  
		session.setDebug(true);
//		      
		Message message = new MimeMessage(session);   
		try 
		{   
//			        
			message.setSubject(EmailMessage.Email_Subject);   
//			          
			message.setHeader("Header", EmailMessage.Email_Header); 
//			           
			message.setSentDate(EmailMessage.sendDate);
			
//			              
			Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);   
//			            
			message.setFrom(address);   
			
//			       
			Address toAddress = new InternetAddress(EmailMessage.TO); 
//			        
			message.setRecipient(Message.RecipientType.TO, toAddress);   
		  
//		 	            
//		 	message.addRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));   

//			       
			message.setContent("Content", EmailMessage.Email_Content); 
//			                      
			message.setText(EmailMessage.Email_Body); 
			
//			         
			message.saveChanges();   
//			      
			System.out.println("sendNormalEmail()       ……");   
			Transport.send(message);   
			System.out.println("    !");   
		} catch (Exception e)
		{   
				System.out.println("  ");   
				e.printStackTrace();   
		}   
	}   
	
	/**
	 *   HTML     
	 */
	public void doSendHtmlMail() 
	{   
//		         
		Properties prop = new Properties();  

		Authenticator auth = null;
		if (EmailMessage.validate)
		{
//			                 
			auth = new MailAuthenticator();
		}
//		       
		prop.put("mail.smtp.host", EmailMessage.Email_Host);   
		prop.put("mail.smtp.auth", "true");   
		
//		               
		Session session = Session.getDefaultInstance(prop, auth);   
		
//		      
		Message message = new MimeMessage(session);   
		try 
		{   
//			        
			message.setSubject(EmailMessage.Email_Subject);   
//			          
			message.setHeader("Header", EmailMessage.Email_Header); 
//			           
			message.setSentDate(EmailMessage.sendDate);
			
//			              
			Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);   
//			            
			message.setFrom(address);   
			
//			       
			Address toAddress = new InternetAddress(EmailMessage.TO); 
//			        
			message.setRecipient(Message.RecipientType.TO, toAddress);   
		  
//		 	            
//		 	message.addRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));   

//			                 hmml
//			      
			EmailMessage.Email_Content = "text/html; charset=utf-8";
			message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content); 

//			         
			message.saveChanges();   
//			      
			System.out.println("doSendHtmlMail()       ……");   
			Transport.send(message);   
			System.out.println("    !");   
		} catch (Exception e)
		{   
				System.out.println("  ");   
				e.printStackTrace();   
		}   
	}   
	/**
	 *            
	 */
	public void doSendAttachmentMail() 
	{   
//		         
		Properties prop = new Properties();  

		Authenticator auth = null;
		if (EmailMessage.validate)
		{
//			                 
			auth = new MailAuthenticator();
		}
//		       
		prop.put("mail.smtp.host", EmailMessage.Email_Host);   
		prop.put("mail.smtp.auth", "true");   
		
//		               
		Session session = Session.getDefaultInstance(prop, auth);   
		
//		      
		Message message = new MimeMessage(session);   
		try 
		{   
//			        
			message.setSubject(EmailMessage.Email_Subject);   
//			          
			message.setHeader("Header", EmailMessage.Email_Header); 
//			           
			message.setSentDate(EmailMessage.sendDate);
			
//			              
			Address address = new InternetAddress(EmailMessage.FROM, EmailMessage.FROM_NAME);   
//			            
			message.setFrom(address);   
			
//			       
			Address toAddress = new InternetAddress(EmailMessage.TO); 
//			        
			message.setRecipient(Message.RecipientType.TO, toAddress);   
		  
//		 	            
//		 	message.addRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));   
		  
			
//			                   
			message.setContent(EmailMessage.Email_Body, EmailMessage.Email_Content); 
			
			BodyPart messageBodyPart = new MimeBodyPart();   
			messageBodyPart.setText("bodypart");   
			
			Multipart multipart = new MimeMultipart();   
			multipart.addBodyPart(messageBodyPart);   
			
			messageBodyPart = new MimeBodyPart();   
			
//			       
			DataSource source = new FileDataSource("E:\\3.doc");  
//			   
			messageBodyPart.setDataHandler(new DataHandler(source));   
//			      ,     
			messageBodyPart.setFileName("test.doc");   
			multipart.addBodyPart(messageBodyPart);  
			
			message.setContent(multipart);   
			
//			         
			message.saveChanges();   
//			      
			System.out.println("doSendAttachmentMail()       ……");   
			Transport.send(message);   
			System.out.println("    !");   
		} catch (Exception e)
		{   
				System.out.println("  ");   
				e.printStackTrace();   
		}   
	}   
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
//		new SendEmail().doSendNormalMail();
//		new SendEmail().doSendHtmlMail();
		new SendEmail().doSendAttachmentMail();
	}

}


実行前にメールの基本情報xxxを自分の持っているメールに変更しなければなりません.
次にソースコードとjarパッケージを添付します.