2018-8-10 #Java

Java Email

STMP协议发送邮件


1.创建 Properties属性对象

if(props == null)
    props = System.getProperties();
 
//设置 服务器 验证 ...
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", prot);
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", password);
props.put("mail.smtp.starttls.enable", "true"); //加密方式??更改影响邮件服务商(这是outlook的)
props.put("mail.smtp.timeout", 1000*30);//I/O连接超时时间 30s
if(validate){//是否需要验证
  props.put("mail.smtp.auth","true");   
}else{   
  props.put("mail.smtp.auth","false");   
} 
 

2.必要参数:

/**
  * 必要参数
  * @param username 用户名
  * @param password 密码
  * @param smtp smtp服务器地址
  * @param prot 端口
  * @param validate 是否需要验证
  */
public EmailManagentSTMP(String username, String password, String smtp, int prot, boolean validate) {
  this.username = username;
  this.password = password;
  this.host = smtp;
  this.prot = prot;
  this.validate = validate;
  createProperties();
}
 

3.创建邮件session

/***
  * 创建邮件session
  * @return
  */
private Session createSession(){
  
  Session s = Session.getDefaultInstance(props,new Authenticator(){
      public PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication(username, password); //发件人邮件用户名, 密码
            }
          });
  
    return s;
}
 

4.发送HTML格式的简单邮件

/**
  * 发送HTML格式的简单邮件
  * 
  * @param to 收件人
  * @param subject主题
  * @param content 文本内容
  * @return 失败false; 成功true
  */
public boolean sendEmail(String to, String subject,String content){
  
  //Session session = Session.getDefaultInstance(props);
  Session session = createSession();
  MimeMessage message = new MimeMessage(session);
    
  try {
  
    // Set From: 头部头字段
    message.setFrom(new InternetAddress(username));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        // Set Subject 内容		
        message.setSubject(subject,"UTF-8");
        message.setContent(content,"text/html;charset=UTF-8" );
 
        // 发送
        Transport.send(message);
        System.out.println("email sent successty.."); 
        return true;
  } catch (AddressException e) {
    //  Auto-generated catch block
    e.printStackTrace();
  } catch (MessagingException e) {
    //  Auto-generated catch block
    e.printStackTrace();
  }
  
  return false;
}
 

4.发送HTML格式带附件邮件

/** 
  * 发送HTML格式,带附件的邮件
  * 
  * @param to 收件人
  * @param subject 主题
  * @param content 文本内容
  * @param files 附件
  * @return 失败false; 成功true
  */
public boolean sendEmail(String to, String subject,String content,File ...files){
 
  Session session = createSession();
  MimeMessage message = new MimeMessage(session);//用以发送的完整信息
    
  try {
  
    // Set From: 头部头字段
    message.setFrom(new InternetAddress(username));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      // Set Subject: 内容
        message.setSubject(subject,"UTF-8");
        // 一个消息体
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content,"text/html;charset=UTF-8" );
        //创建多重消息 (可以存多个消息)
        Multipart multipart = new MimeMultipart();
        // 添加一个消息体
        multipart.addBodyPart(messageBodyPart);
        for(File f: files){
          // 附件部分(一个消息体)
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(f.getAbsolutePath());
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(f.getAbsolutePath());
          // 添加到多重消息体
          multipart.addBodyPart(messageBodyPart);
        }
      // set到完整消息
        message.setContent(multipart);
        // 发送
        Transport.send(message);
        System.out.println("email sent successty.."); 
        
        return true;
  } catch (AddressException e) {
    //  Auto-generated catch block
    e.printStackTrace();
  } catch (MessagingException e) {
    //  Auto-generated catch block
    e.printStackTrace();
  }
  
  return false;
}
 

4.Main

public static void main(String[] args){
  String smtp = "smtp-mail.outlook.com";  
  int prot = 587;
  boolean validate = true;
  String username="helpless.yanglll@hotmail.com"; 
  String password="ppp**p*p*p";
  
  
  EmailManagentSTMP email = new EmailManagentSTMP(username, password, smtp, prot, validate);
  
  String to = "helpless.yang@foxmail.com";
  String subject = "this is subject (中文标题)"; 
  String content = "<p style=\"font-family:verdana;color:red\"> This text is in Verdana and red (中文测试)</p> ";
  @SuppressWarnings("unused")
  File f = new File("f:TEMP/EmailStmp.java");
  
  email.sendEmail(to, subject, content);
  
}
 


POP3协议收邮件


/**
 * 
 * 
 * @author yang
 * 2016年12月23日
 */
public class EmailManagentPOP3 {
 
	//属性对象,用户名& 密码,服务器地址&端口...
	private Properties props = null;
	private String username = null;
	private String password = null;
	private String pop3 = null;	
	private int prot = 465;
 
	/**
	 * 创建Properties属性对象
	 */
	private void createProperties(){
		if(props == null)
			props = System.getProperties();
		props.put("mail.host", pop3);
		props.put("mail.port", prot);
		props.put("mail.user", username);
		props.put("mail.password", password);
		props.put("mail.store.protocol", "imap");
		props.put("mail.starttls.enable", "true"); 	//加密方式??更改影响邮件服务商(适用outlook)
		//props.put("mail.timeout", 1000*30);			//I/O连接超时时间 30s
	}
 
	/***
	 * 获得邮件session
	 * 
	 * @return
	 */
	private Session getSession(){
		
		Session s = Session.getInstance(props);
		return s;
	}
	
	/**
	 *  必要参数 
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param pop3 pop3服务器地址
	 * @param prot 端口
	 */
	public EmailManagentPOP3(String username, String password, String pop3, int prot) {
		this.username = username;
		this.password = password;
		this.pop3 = pop3;
		this.prot = prot;
		createProperties();
	}
 
	/**
	 * 获得第一封邮件
	 * 
	 * @return
	 */
	public Message getFirstMessage(){
		
		IMAPStore store =  null;//获取并连接一个用于邮箱的适宜的存储(store)
		IMAPFolder folder = null;//收件箱  
		
		try {
			store = (IMAPStore) this.getSession().getStore("imap");// 使用imap会话机制, 连接服务器  
			//store.connect(props.getProperty("mail.user"), props.getProperty("mail.password"));  
			store.connect(username,password ); 
			
			folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱  
 
	        /* Folder.READ_ONLY: 只读权限
	         * Folder.READ_WRITE: 可读可写(可以修改邮件的状态)
	         */ 
	        folder.open(Folder.READ_WRITE); //打开收件箱 
	        // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数 
	        System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
	        // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0 
	        System.out.println("删除邮件数: " + folder.getDeletedMessageCount()); 
	        System.out.println("新邮件: " + folder.getNewMessageCount()); 
	         
	        // 获得收件箱中的邮件总数 
	        System.out.println("邮件总数: " + folder.getMessageCount()); 
	         
	        // 得到收件箱中的所有邮件,并解析 
	        Message[] messages = folder.getMessages(); 
	        
	        for (int i = 0, count = messages.length; i < count; i++) { 
	            MimeMessage msg = (MimeMessage) messages[i]; 
	            System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- "); 
	            System.out.println("主题: " + MimeUtility.decodeText(msg.getSubject())); 
	            System.out.println("发件人: " + msg.getFrom()); 
	            System.out.println("收件人: " + msg.getReplyTo()); 
	            System.out.println("发送时间: " + msg.getSentDate()); 
	            System.out.println("是否已读: " + msg.getFlags().contains(Flags.Flag.SEEN)); 
	            System.out.println("邮件大小: " + msg.getSize() * 1024 + "kb"); 
	            
	            System.out.println("邮件正文: " + msg.getContent()); 
	            System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- "); 
			
	        }
		} catch ( NoSuchProviderException  e) {
			//  Auto-generated catch block
			e.printStackTrace();
		 
		} catch ( MessagingException  e) {
			//  Auto-generated catch block
			e.printStackTrace();
			
			
		} catch (IOException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if (folder != null)
						folder.close(true);
					
					if (store != null)  
				        store.close();  
					
				} catch (MessagingException e) {
					//  Auto-generated catch block
					e.printStackTrace();
				} 
		}
		return null;
		
	}
	
	
	public static void main(String[] args) {
		
		String imap = "pop-mail.outlook.com";  
		int prot = 995;
		String username="helpless.yanglll@hotmail.com"; 
		String password="2122222";
		
		EmailManagentIMAP email = new EmailManagentIMAP(username, password, imap, prot);
		System.out.println("begin");
		email.getFirstMessage();
	}
}


IMAP协议收邮件


/**
 * 
 * 
 * @author yang
 * 2016年12月23日
 */
public class EmailManagentIMAP {
 
	//属性对象,用户名& 密码,服务器地址&端口...
	private Properties props = null;
	private String username = null;
	private String password = null;
	private String imap = null;	
	private int prot = 465;
 
	/**
	 * 创建Properties属性对象
	 */
	private void createProperties(){
		if(props == null)
			props = System.getProperties();
		props.put("mail.host", imap);
		props.put("mail.port", prot);
		props.put("mail.user", username);
		props.put("mail.password", password);
		props.put("mail.store.protocol", "imap");
		//props.put("mail.starttls.enable", "true"); 	//加密方式??更改影响邮件服务商(适用outlook)
		//props.put("mail.timeout", 1000*30);			//I/O连接超时时间 30s
	}
 
	/***
	 * 获得邮件session
	 * 
	 * @return
	 */
	private Session getSession(){
		
		Session s = Session.getInstance(props);
		return s;
	}
	
	/**
	 *  必要参数 
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param imap imap服务器地址
	 * @param prot 端口
	 */
	public EmailManagentIMAP(String username, String password, String imap, int prot) {
		this.username = username;
		this.password = password;
		this.imap = imap;
		this.prot = prot;
		createProperties();
	}
 
	/**
	 * 获得第一封邮件
	 * 
	 * @return
	 */
	public Message getFirstMessage(){
		
		IMAPStore store =  null;//获取并连接一个用于邮箱的适宜的存储(store)
		IMAPFolder folder = null;//收件箱  
		
		try {
			store = (IMAPStore) this.getSession().getStore("imap");// 使用imap会话机制, 连接服务器  
			//store.connect(props.getProperty("mail.user"), props.getProperty("mail.password"));  
			store.connect(username,password ); 
			folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱 
			folder.open(Folder.READ_WRITE);  
		    int total = folder.getMessageCount();   // 获取总邮件数  
			 
		    System.out.println("-----------------共有邮件: " + total   + " 封--------------");  
		    System.out.println("未读邮件数: " + folder.getUnreadMessageCount());  
		    Message[] messages = folder.getMessages();  
	        int messageNumber = 0;  
	        for (Message message: messages) {  
	            System.out.println("发送时间: " + message.getSentDate());  
	            System.out.println("主题: " + message.getSubject());  
	            System.out.println("内容: " + message.getContent());  
	            Flags flags = message.getFlags();  
	            if (flags.contains(Flags.Flag.SEEN))  
	                System.out.println("这是一封已读邮件");  
	            else {  
	                System.out.println("未读邮件");  
	            }  
	            System.out.println("========================================================");  
	            System.out.println("========================================================");  
	            //每封邮件都有一个MessageNumber, 可以通过邮件的MessageNumber在收件箱里面取得该邮件  
	            messageNumber = message.getMessageNumber();  
	        }
	        Message message = folder.getMessage(messageNumber);  
	        System.out.println(message.getContent()+message.getContentType());  
	        
		} catch ( NoSuchProviderException  e) {
			//  Auto-generated catch block
			e.printStackTrace();
		 
		} catch ( MessagingException  e) {
			//  Auto-generated catch block
			e.printStackTrace();
			
			
		} catch (IOException e) {
			//  Auto-generated catch block
			e.printStackTrace();
		}finally{
				try {
					if (folder != null)
						folder.close(true);
					if (store != null)  
				        store.close();  
				} catch (MessagingException e) {
					//  Auto-generated catch block
					e.printStackTrace();
				}   
	      
		}
		return null;
		
	}
 
	
	public static void main(String[] args) {
		
		String imap = "imap-mail.outlook.com";  
		int prot = 993;
		String username="helpless.yanglll@hotmail.com"; 
		String password="PPPPPP";
		
		EmailManagentIMAP email = new EmailManagentIMAP(username, password, imap, prot);
		System.out.println("begin");
		email.getFirstMessage();
	}
}