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() ;
}
}