javaMail发送邮件(支持单发、群发)

1.所需夹包:javaMail.jar 、activation.jar

2.实现步骤:

(1).定义一个邮件消息类;

(2).定义一个服务器邮箱登录验证信息类;

(3).定义一个邮件发送类(核心类)

3.具体代码:

package cn.my.utils;

import java.util.List;


/**
 * 邮件发送的信息实体类@date 2014.10.13
 *  @author wangbowen
 *  @version 1.0
 * 
 */
public class SimpleMail {
	
	/**
	 * 发送邮件者的地址
	 */
	public String fromAddress;
	/**
	 * 登录邮件服务器的用户名
	 */
	public String userName;
	/**
	 * 登录邮件服务器的密码
	 */
	public String userPassword;

	/**
	 * 接受邮件者的地址
	 */
	public String toAddress;
	/**
	 * 多个接受邮件者地址
	 */
	public List  recipients;
	/**
	 * 接受邮件的主题
	 */
	public String subject;
	/**
	 * 邮件的内容
	 */
	public String content;

	


	

	/**
	 * @return the fromAddress
	 */
	public String getFromAddress() {
		return fromAddress;
	}

	/**
	 * @param fromAddress
	 *            the fromAddress to set
	 */
	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	/**
	 * @return the userName
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * @param userName
	 *            the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @return the userPassword
	 */
	public String getUserPassword() {
		return userPassword;
	}

	/**
	 * @param userPassword
	 *            the userPassword to set
	 */
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	/**
	 * @return the toAddress
	 */
	public String getToAddress() {
		return toAddress;
	}

	/**
	 * @param toAddress
	 *            the toAddress to set
	 */
	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	/**
	 * @return the subject
	 */
	public String getSubject() {
		return subject;
	}

	/**
	 * @param subject
	 *            the subject to set
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * @return the content
	 */
	public String getContent() {
		return content;
	}

	/**
	 * @param content
	 *            the content to set
	 */
	public void setContent(String content) {
		this.content = content;
	}

 
/**
	 * @return the recipients
	 */
	public List getRecipients() {
		return recipients;
	}

	/**
	 * @param recipients the recipients to set
	 */
	public void setRecipients(List recipients) {
		this.recipients = recipients;
	}

public	SimpleMail(List recipients, String subject, String content) {
	
		this.recipients = recipients;
		this.subject = subject;
		this.content = content;
	}

}

package cn.my.utils;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
 * 服务器邮箱登录验证
 * @author [email protected]
 * @version 1.0
 *
 */
public class MailAuthenticator  extends Authenticator {
    /**
     * 用户名(登录邮箱)
     */
 private String userName = null;
	/**
	 * 密码
	 */
 private String userPass = null;
	/**
	 * 无参
	 */
	public MailAuthenticator() {
	}
	/**
	 * 初始化邮箱和密码
	 * @param userName 用户名
	 * @param userPass 密码
	 */
	public MailAuthenticator(String userName, String userPass) {
		this.userName = userName;
		this.userPass = userPass;
	}
	/**
	 * 取值
	 * @return ""
	 */
	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(userName, userPass);
	}
	/**
	 * @return the userName
	 */
	public String getUserName() {
		return userName;
	}
	/**
	 * @param userName the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}
	/**
	 * @return the userPass
	 */
	public String getUserPass() {
		return userPass;
	}
	/**
	 * @param userPass the userPass to set
	 */
	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}
	
}

package cn.my.utils;
 
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
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;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeMessage.RecipientType;
 
/**
 * 简单邮件发送器,可单发,群发@date 2014.10.13。
 * @author wangbowen
 * @version 1.0
 * 
 */
public class SimpleMailSender {
 
    /**
     * 发送邮件的props文件
     */
     public  Properties props;
     /**
      * DUANKOU
      */
     public static final int mailserverport = 25;
    /**
     * 邮件服务器登录验证
     */
     public transient MailAuthenticator authenticator;
 
    /**
     * 邮箱session
     */
     public  Session session;
     
     
     public Transport transport;
 
    /**
     * 初始化邮件发送器
     * 
     * @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服务器,对大多数邮箱都管用
     String str = username.split("@")[1];
     String smtpHostName  = "smtp." +str;
    init(username, password, smtpHostName);
 
    }
 
    /**
     * 初始化
     * 
     * @param username
     *                发送邮件的用户名(地址)
     * @param password
     *                密码
     * @param smtpHostName
     *                SMTP主机地址
     */
    private void init(String username, String password, String smtpHostName) {
 
    	   // 初始化props
    	props = new Properties();
        props.put("mail.smtp.host", smtpHostName);
        props.put("mail.smtp.port",String.valueOf(mailserverport) );
        props.put("mail.smtp.starttls.enable","true" );
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", String.valueOf(mailserverport));
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.from", username);
        LoggerUtils.info("初始化props成功....");
        // 验证
        authenticator = new MailAuthenticator(username, password);
        // 创建session
        session = Session.getDefaultInstance(props, authenticator);
 
    }
 
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param subject
     *                邮件主题
     * @param content
     *                邮件内容
     * @throws AddressException
     * @throws MessagingException
     */
    @SuppressWarnings("static-access")
	public void sendOne(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");
    message.saveChanges();
    // 发送
    transport = session.getTransport((String) props.get("mail.transport.protocol"));  
    // 真正的连接邮件服务器并进行身份验证  
    transport.connect("smtp."+authenticator.getUserName().split("@")[1],authenticator.getUserName(),authenticator.getUserPass());  
    transport.send(message);  
    
    }
 
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param subject
     *                主题
     * @param content
     *                内容
     * @throws AddressException
     * @throws MessagingException
     */
	@SuppressWarnings("static-access")
	public boolean send(List recipients, String subject, Object content)
        throws AddressException, MessagingException {
     try{
    // 创建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");
    //发送时间
    message.setSentDate(new Date());
    message.saveChanges();  
    // 发送
    transport = session.getTransport((String) props.get("mail.transport.protocol"));  
    // 真正的连接邮件服务器并进行身份验证  
    transport.connect("smtp."+authenticator.getUserName().split("@")[1],authenticator.getUserName(),authenticator.getUserPass());  
    transport.send(message);  
    LoggerUtils.info("发送成功....");
     transport.close();
     }catch(Exception e){
    	 e.printStackTrace();
    	 LoggerUtils.info("发送失败....");
    	 return false;
     }
     return true;
    }
    
	
	 /**
     * 群发邮件含附件
     * 
     * @param recipients
     *                收件人们
     * @param subject
     *                主题
     * @param content
     *                内容
     * @param filepath 附件
     * @throws AddressException
     * @throws MessagingException
     */
	@SuppressWarnings("static-access")
	public boolean sendMail(List recipients, String subject, Object content,String filepath)
        throws AddressException, MessagingException {
     try{
    // 创建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);
    Multipart m = new MimeMultipart();
    BodyPart bp = new MimeBodyPart();
    bp.setContent(content.toString(), "text/html; charset=utf-8");
    // 加入附件
    FileDataSource ds = new FileDataSource(filepath);
    bp.setDataHandler(new DataHandler(ds));
    bp.setFileName(MimeUtility.encodeText(ds.getName()));
    m.addBodyPart(bp);
   // 设置邮件内容
    message.setContent(m);
    //发送时间
    message.setSentDate(new Date());
    message.saveChanges();  
    // 发送
    transport = session.getTransport((String) props.get("mail.transport.protocol"));  
    // 真正的连接邮件服务器并进行身份验证  
    transport.connect("smtp."+authenticator.getUserName().split("@")[1],authenticator.getUserName(),authenticator.getUserPass());  
    transport.send(message);  
    LoggerUtils.info("发送成功....");
     transport.close();
     }catch(Exception e){
    	 e.printStackTrace();
    	 LoggerUtils.info("发送失败....");
    	 return false;
     }
     return true;
    }
    
    /**
     * 发送邮件
     * 
     * @param recipient
     *                收件人邮箱地址
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public void send(String recipient, SimpleMail mail)
        throws AddressException, MessagingException {
    sendOne(recipient, mail.getSubject(), mail.getContent());
    }
 
    /**
     * 群发邮件
     * 
     * @param recipients
     *                收件人们
     * @param mail
     *                邮件对象
     * @throws AddressException
     * @throws MessagingException
     */
    public boolean sendMails(SimpleMail mail)
        throws AddressException, MessagingException {
      boolean sendResult =  send(mail.getRecipients(),mail.getSubject(), mail.getContent());
      if(sendResult){
    	  return true;
      }
      return false;
    }
    /**
     * 异步发送邮件
     * @param mail 邮件对象
     * @return
     */
    public void sendMailByAsynchronous(final SimpleMail mail){
    	 new Thread(new Runnable() {  
             public void run() {  
                 try {  
                	 send(mail.getRecipients(),mail.getSubject(), mail.getContent()); 
                 } catch (Exception ex) {  
                     LoggerUtils.error("邮件发送失败"+ex);  
                 }  
             }  
         }).start();
    }
}


 
  
package cn.my.utils;


import java.util.ArrayList;
import java.util.List;


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


/**
 * 测试邮件发送
 * @author wangbowen
 *
 */
public class test {
public static void main(String[] args) {

try {
	//分割邮件
	String [] arrayemail ={"[email protected]","[email protected]"};
	//接受邮件者
	List recipients = new ArrayList();
	for (int j = 0; j < arrayemail.length; j++) {
	recipients.add(arrayemail[j]);
	}
//从properties文件中读取邮件发送者的邮箱以及密码
String userName = PropertiesUtil.findData("usermail.properties", "mail.username");
   String password = PropertiesUtil.findData("usermail.properties", "mail.password");
SimpleMailSender sm = new SimpleMailSender(userName,password);
sm.sendMails(new SimpleMail(recipients,"通知","成功"));
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

5.mail.properties文件,可以根据你自己的需要设置相应的用户邮箱和密码
[email protected]
mail.password=123456

6.注意:使用qq邮箱发送邮件需要设置SMTP开启服务

第一步,看图操作如下:

javaMail发送邮件(支持单发、群发)_第1张图片

打开QQ邮箱,在设置-帐户,然后再看下图示:

javaMail发送邮件(支持单发、群发)_第2张图片

把:POP3/SMTP服务,IMAP/SMTP服务,Exchange服务,CardDAV/CalDAV服务都选择上,保存这样,便可以轻松使用邮箱客户端来收发QQ邮件了!相关OUTLOOK设置如下:

javaMail发送邮件(支持单发、群发)_第3张图片

可以看到,填写好接收邮件服务器:pop.qq.com,发送邮件服务器:smtp.qq.com;然后用户名与密码,设置好了后,便可以收QQ邮件了;


 
  
<

你可能感兴趣的:(java,javaMail,发送邮件)