java mail 发送邮件

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

import javax.mail.Message;
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;

/**
 *  use java mail send and store mail
 *  
 *  (1) create Properties
 *  	mail.smtp.host:mail host
 *  	mail.smtp.auth:mail auth
 *  (2) create session :Session.getDefaultInstance(pro)
 *	    session.setDebug(true) show debug information
 *	(3)create MimeMessage
 *		from:send mail people(new InterneyAddress())
 *		Recipient:Message.RecipientType.TO,InternetAddress(to)
 *		subject:mail subject
 *      text:mail content
 *      date: send mail date
 *      saveChanges:save mail to box		
 *  (4)create Transport object to send message 
 *  	connection mail host use host,user,password
 *  	sendMessage
 *  	close
 *
 */	
public class MailSend {
	
	public void send(){
		//首先创建Properties对象
		Properties pro = new Properties() ;
		pro.put("mail.smtp.host", "smtp.qq.com") ;   //mail host
		pro.put("mail.smtp.auth", "true") ;          //authencaitor user
		
		//创建session对象
		Session session = Session.getDefaultInstance(pro) ;  //mail session
		session.setDebug(true) ;
		//创建MimeMessage对象
		MimeMessage message = new MimeMessage(session) ;
		try {
			message.setFrom(new InternetAddress("********@qq.com")) ;  //from 
			message.setRecipient(Message.RecipientType.TO, new InternetAddress("******@163.com")) ; //to
			
			message.setSubject("java mail test") ;    //mail subject
			message.setText("哈哈,这个是使用javaMail从qq邮箱发过来的邮件") ;  //mail content
			message.setSentDate(new Date()) ;      //mail send date
			message.saveChanges() ;   //save message to saveBox
			
			//创建发送邮件的Transport
			Transport tranport =  session.getTransport("smtp") ;  
			tranport.connect("smtp.qq.com", "qq_username", "qq_mail_password") ; //connect mail server
			tranport.sendMessage(message, message.getAllRecipients()) ;//send message  //first parameter is :message
			                                                             //second parameter is cc
			
			tranport.close() ;
 		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
 	}
	//parse mail host from mail address
	public String getMailHost(String from){
		String mail_host = "stmp." ;
		mail_host += from.substring(from.lastIndexOf("@")+1,from.length()) ;
		return mail_host ;
	}
	public static void main(String [] args){
		MailSend mailSend = new MailSend() ;
		mailSend.send() ;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值