Thứ Hai, 1 tháng 8, 2011

Gửi Mail trong Java

Cuối cùng vất vả cả buổi tối mới làm xong cái send mail
Ghi lại vài bữa có lúc dùng tới..Code cho nhanh


Tạo file SendMail.java
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


import java.util.*;
public class SendMailApp {
private final String host = "smtp.gmail.com";
private final String port = "587";
private final String to = "vantientran.it@gmail.com";
private String from="";
private String subject="";
private String content="";
public SendMailApp(String from,String subject,String content){
this.from = from;
this.subject = subject;
this.content = content;
}
public void Send() throws Exception{
Properties props = System.getProperties();
props.put("mail.host", this.host);
props.put("mail.smtp.port",this.port);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable","true");
Authenticator pa = null;
props.put("mail.smtp.auth", "true");
pa = new Authenticator (){
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("EmailCanGuiDen", "MatKhauTruyCapEmail");
}
};
Session mailSession = Session.getInstance(props, pa);
Message msg = new MimeMessage(mailSession);
msg.setSubject(this.subject);
msg.setSentDate(new Date());
msg.setText(this.content);
msg.setFrom(new InternetAddress(this.from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(this.to));
Transport.send(msg);
}

}

Không có nhận xét nào:

Đăng nhận xét