关于java发送email案例

1.先创建一个Email所用到的信息类:

package com.tan.test;

import java.util.Properties;

/**
 * 功能:邮箱信息类
 * @author TanZi
 * @time 2015-4-20上午10:35:47
 */
public class MailSenderInfo {

	//发送邮件的服务器验证需要的信息
	private String mailServerHost;  //服务器的IP地址
	private String mailServerPort;  //端口号
	//发送者的信息
	private String formAddress;  //发送者的地址
	private String userName;//  发送者的帐号
	private String password;//	发送者的pndc
	//接收者
	private String toAddress;//	接收者的地址
	//发送的主题
	private String subject;
	//发送的内容
	private String content;
	
	/**
	 * 功能:获得邮件会话属性
	 * @return
	 */
	public Properties getProperties(){
		Properties properties=new Properties();
		properties.put("mail.smtp.host", this.mailServerHost);  //主机地址
		properties.put("mail.smtp.port", this.mailServerPort);  //端口号
		properties.put("mail.smtp.auth", "true");            //设置发送授权认证
		return properties;
	}
	
	
	//------------------getter/setter-------------------
	public String getMailServerHost() {
		return mailServerHost;
	}
	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}
	public String getMailServerPort() {
		return mailServerPort;
	}
	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}
	public String getFormAddress() {
		return formAddress;
	}
	public void setFormAddress(String formAddress) {
		this.formAddress = formAddress;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getToAddress() {
		return toAddress;
	}
	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
	
	
}

2.创建继承、重写认证方法

package com.tan.test;

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

/**
 * 功能:身份验证类——邮箱帐户和密码的验证
 * @author TanZi
 * @time 2015-4-20上午10:52:17
 */
public class MyAuthenticator extends Authenticator{

	String username=null;
	String password=null;
	
	public MyAuthenticator(){	}
	
	public MyAuthenticator(String username,String passowrd){
		this.username=username;
		this.password=passowrd;
	}
	
	/**
	 * 用户名和密码验证
	 */
	public PasswordAuthentication getPasswordAuthentication(){
		return new PasswordAuthentication(username, password);
	}
}

3.编写发email发核心类(怎么装载数据。怎么发送)

package com.tan.test;

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.Address;
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;

/**
 * 功能:邮件发送的核心类
 * @author TanZi
 * @time 2015-4-20上午11:02:26
 */
public class SimleMailSender {

	/**
	 * 功能:邮件发送的核心方法
	 * @param mailInfo  邮件信息类
	 * @return boolean
	 */
	public boolean sendHtmlMail(MailSenderInfo mailInfo){
		
		
		MyAuthenticator authenticator=new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());//身份验证
		Properties properties=mailInfo.getProperties();   
		//根据邮件会话属性和验证器构造一个发送邮件的session
		Session sendMailSession=Session.getDefaultInstance(properties, authenticator);
		
		
		
		try {
			//定义发送邮件的主体
			Message mailMessage=new MimeMessage(sendMailSession);
			//创建发送者的地址
			Address fromAddress=new InternetAddress(mailInfo.getFormAddress());
			//设置邮件消息的发送者
			mailMessage.setFrom(fromAddress);
			//创建接受者的地址
			Address toAddress=new InternetAddress(mailInfo.getToAddress());
			//创建邮件消息的接受者
			mailMessage.setRecipient(Message.RecipientType.TO, toAddress);//BCC:密送..CC:抄送.. TO:直接发送
			
			//邮件的主题
			mailMessage.setSubject(mailInfo.getSubject());
			//设置邮件发送的时间
			mailMessage.setSentDate(new Date());
			//设置邮件消息的主要内容
		//	String mailContent=mailInfo.getContent();
			//创建一个容器
			Multipart maimPart=new MimeMultipart();
			//创建一个包含html内容的MimeBodyPart
			BodyPart html=new MimeBodyPart();
			//设置html的邮件内容
			html.setContent(mailInfo.getContent(),"text/html;charset=utf-8");
			maimPart.addBodyPart(html);
			//创建附件
			BodyPart attach=new MimeBodyPart();
			DataSource source=new FileDataSource("E:\\Code\\Movie\\images\\four.jpg");//加载要作为附件的文件
			attach.setDataHandler(new DataHandler(source));
			attach.setFileName("four.jpg");
			maimPart.addBodyPart(attach);
			
			//设置内容
			mailMessage.setContent(maimPart);
			//设置 发送html格式的邮件头信息
			MailcapCommandMap mc=(MailcapCommandMap) CommandMap.getDefaultCommandMap();
			 mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
		     mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
		     mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
		     mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
		     mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
		     CommandMap.setDefaultCommandMap(mc);
		     //发送文件
		     Transport.send(mailMessage);
		     return true;
		} catch (AddressException e) {
			
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	     return false;
	}
}
4。测试类

package com.tan.test;

/**
 * 功能:
 * @author TanZi
 * @time 2015-4-20下午1:16:15
 */
public class TestMail {

	/**
	 * 功能:
	 * @param args
	 */
	public static void main(String[] args) {
MailSenderInfo mailInfo = new MailSenderInfo();
		System.out.println("");
		mailInfo.setMailServerHost("smtp.qq.com"); // 邮件服务器主机
		mailInfo.setMailServerPort("25"); // 服务器端口  SMTP:单单的邮件传输协议  端口:25
		
		mailInfo.setUserName("571868789"); // 发送者用户名
		mailInfo.setPassword("tanliu1234"); // 发送者密码
		mailInfo.setFormAddress("[email protected]"); //发送者地址
	
		
		//mailInfo.setToAddress("[email protected]"); // 接收者地址
		String toAddress = "[email protected]";
		mailInfo.setToAddress(toAddress);
		
		
		String subject = "TanZi-------text"; // 主题
		
		String  content = "<a  href='http://blog.csdn.net/u011707402' >";
		 content  += "<div style='width:650px;background-color:#DBDBFF;";
		 content  += "text-align:center;color:red;font-size:20px;border:0 solid red;'>";
		 content  +="<b>恭喜你收到我的信息<br />";
		 content  +="<a href='http://blog.csdn.net/u011707402'>坛子成长记学习知识</a><br />";
		 content  +="坛子";
		 content  +="</b><img width='100%' src='http://www.nipic.com/show/7364191.html' /></div></a>";

		
		mailInfo.setSubject(subject);
		mailInfo.setContent(content);
		
		SimleMailSender sms = new SimleMailSender();
		boolean flag = sms.sendHtmlMail(mailInfo); // 发送邮件
		if(flag){
			System.out.println("成功!");
		}else{
			System.out.println("失败!");
		}
	}

}

5.注意事项

  1. 发送邮件错误 454 Authentication failed, please open smtp flag first!

     ----(方法)在QQ邮箱的设置里面,找到账户-》POP3/IMAP/SMTP选择开启POP3/SMTP服务
  2. 535 Authentication failed(原因):帐号和密码错误




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。