java实现邮件的发送及接收

package com.self.uitls;

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

import javax.mail.Authenticator; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.search.FlagTerm;

import org.junit.Test;

import com.sun.mail.util.MailSSLSocketFactory;

/** * 发送邮件 * setRecipient(Message.RecipientType type , Address theAddress)、setRecipients(Message.RecipientType type , Address[] theAddress)、addRecipient(Message.RecipientType type , Address theAddress)、addRecipients(Message.RecipientType type,Address[] theAddress)方法都可以指定接受者类型,但是一般用后两个,这样可以避免意外的替换或者覆盖接受者名单。定义接受者类型: *Message.RecipientType.TO:消息接受者 *Message.RecipientType.CC:消息抄送者 *Message.RecipientType.BCC:匿名抄送接收者(其他接受者看不到这个接受者的姓名和地址) * @author rhy * @date 2018-7-23 下午3:11:05 * @version V1.0 */ public class MailUtil {

/** * 163邮箱 * * @param args */ public static void main(String[] args) {

try { // 创建一个程序与邮件服务器会话对象session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP"); props.setProperty("mail.smtp.host", "smtp.163.com"); props.setProperty("mail.smtp.port", "25"); // 指定验证为true props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.timeout", "4000");

// 验证账号及密码,密码需要是第三方授权码 Authenticator auth = new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("xxxx@163.com", "xxxxx"); } };

e.printStackTrace(); } }

// 验证账号及密码,密码需要是第三方授权码 Authenticator auth = new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {

e.printStackTrace(); } }

// jmiifibifvpfbaii

// 使用ssl,企业邮箱必需 // 开启安全协议 MailSSLSocketFactory sf = null; try {

sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); } catch (Exception e) { e.printStackTrace(); }

props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.socketFactory", sf);

Session session = Session.getDefaultInstance(props, new Authenticator() {

@Override protected PasswordAuthentication getPasswordAuthentication() {

PasswordAuthentication pa = new PasswordAuthentication( "xxxx@easyinfo.net.cn", "xxxx"); return pa; } });

// 设置session的调试模式 session.setDebug(true);

MimeMessage mimeMessage = new MimeMessage(session);

// 发送 Transport.send(mimeMessage); } catch (Exception e) {

e.printStackTrace(); } }

经验分享 程序员 微信小程序 职场和发展