java邮件的发送

最近因项目的需要,做了注册邮件验证的功能,所以整理了一下java简单的邮件发送,需要用的mail.jar 请自己在网上下载


一。定义一个封装邮件内容的类,代码如下

package net.bolue.mail;

/**
 * 简单邮件
 * @author bruisefree
 *
 */
public class SimpleMail {
	protected String subject;//邮件主题
	protected String content;//邮件内容
	
	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;
	}
}



二,定义验证邮件的实体类,即用来验证邮件地址和密码是否可用

package net.bolue.mail;

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

/**
 * 邮箱验证实体
 * @author bruisefree
 *
 */
public class MailAuthenticator extends Authenticator{
	/**
	 * 用户名(登录邮箱)
	 */
	private String username;
	/**
	 * 密码
	 */
	private String password;

	/**
	 * 初始化邮箱和密码
	 * 
	 * @param username
	 *            邮箱
	 * @param password
	 *            密码
	 */
	public MailAuthenticator(String username, String password) {
		this.username = username;
		this.password = password;
	}

	String getPassword() {
		return password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, password);
	}

	String getUsername() {
		return username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}





三。就是编写我们真正用来发送邮件的类
package net.bolue.mail;

import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMessage.RecipientType; 
/**
 * 发送邮件的类
 * @author Administrator
 *
 */
public class SimpleMailSender {
	/**
     * 发送邮件的props文件
     */
    private final transient Properties props = System.getProperties();
    /**
     * 邮件服务器登录验证
     */
    private transient MailAuthenticator authenticator;
  
    /**
     * 邮箱session
     */
    private transient Session session;
  
    /**
     * 初始化邮件发送器
     * 
     * @param smtpHostName
     *                SMTP邮件服务器地址
     * @param username
     *                发送邮件的用户名(地址)
     * @param password
     *                发送邮件的密码
     */
    public SimpleMailSender(final String smtpHostName,final String username,
        final String password) {
    	init(username, password, smtpHostName);
    }
  
    /**
     * 初始化邮件发送器
     * 
     * @param username
     *                发送邮件的用户名(地址),并以此解析SMTP服务器地址
     * @param password
     *                发送邮件的密码
     */
    public SimpleMailSender(final String username,final String password) {
	    //通过邮箱地址解析出smtp服务器,对大多数邮箱都管用
	    final String smtpHostName ="smtp."+ username.split("@")[1];
	    init(username, password, smtpHostName);
    }
  
    /**
     * 初始化
     * 
     * @param username
     *                发送邮件的用户名(地址)
     * @param password
     *                密码
     * @param smtpHostName
     *                SMTP主机地址
     */
    private void init(String username, String password, String smtpHostName) {
	    // 初始化props
	    props.put("mail.smtp.auth","true");
	    props.put("mail.smtp.host", smtpHostName);
	    // 验证
	    authenticator =new MailAuthenticator(username, password);
	    // 创建session
	    session = Session.getInstance(props, authenticator);
    }
  
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param subject
     *                邮件主题
     * @param content
     *                邮件内容
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String recipient, String subject, Object content)  throws AddressException, MessagingException {
	    // 创建mime类型邮件
	    final MimeMessage message =new MimeMessage(session);
	    // 设置发信人
	    message.setFrom(new InternetAddress(authenticator.getUsername()));
	    // 设置收件人
	    message.setRecipient(RecipientType.TO,new InternetAddress(recipient));
	    // 设置主题
	    message.setSubject(subject);
	    // 设置邮件内容
	    message.setContent(content.toString(),"text/html;charset=utf-8");
	    // 发送
	    Transport.send(message);
    }
  
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param subject
     *                主题
     * @param content
     *                内容
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(List<String> recipients, String subject, Object content)
        throws AddressException, MessagingException {
	    // 创建mime类型邮件
	    final MimeMessage message =new MimeMessage(session);
	    // 设置发信人
	    message.setFrom(new InternetAddress(authenticator.getUsername()));
	    // 设置收件人们
	    final int num = recipients.size();
	    InternetAddress[] addresses =new InternetAddress[num];
	    for(int i =0; i < num; i++) {
	        addresses[i] =new InternetAddress(recipients.get(i));
	    }
	    message.setRecipients(RecipientType.TO, addresses);
	    // 设置主题
	    message.setSubject(subject);
	    // 设置邮件内容
	    message.setContent(content.toString(),"text/html;charset=utf-8");
	    // 发送
	    Transport.send(message);
    }
  
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String recipient, SimpleMail mail) throws AddressException, MessagingException {
    	send(recipient, mail.getSubject(), mail.getContent());
    }
  
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(List<String> recipients, SimpleMail mail)
        throws AddressException, MessagingException {
    	send(recipients, mail.getSubject(), mail.getContent());
    }
  

}



好了,下面我们来写个测试类来发送邮件

package net.bolue.mail;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

public class MailSendFactory {
	/** 
     * 服务邮箱 
     */
    private static SimpleMailSender serviceSms = null; 
  
    /** 
     * 获取邮箱 
     *  
     * @param type 邮箱类型 
     * @return 符合类型的邮箱 
     */
    public static SimpleMailSender getSender() {
	        if (serviceSms == null) {
	        serviceSms = new SimpleMailSender("[email protected]",   "123456"); 
	        } 
	        return serviceSms; 
    }
    
    
    public static void main(String[] args) throws AddressException, MessagingException{
    	SimpleMailSender mailSender = MailSendFactory.getSender();
    	SimpleMail mail = new SimpleMail();
    	mail.setContent("你可以收到邮件了");
    	mail.setSubject("邮件测试");
    	mailSender.send("[email protected]", mail);
    }

}



好了可以成功收到短信了,在myeclipse下编写此功能的时候可能会无法成功,并且报错,如果发生错误可能是jar包冲突,那么你删除myeclipse下自带的mail功能的jar包即可

你可能感兴趣的:(java 邮件 smtp)