Send mail dùng SMTP
class MailAuthenticator.java
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
/**
*
* @author tronghiencao
*/
public class MailAuthenticator extends Authenticator {
private final String user;
private final String password;
public MailAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.user, this.password);
}
}
class SendMailExample.java
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author tronghiencao
*/
public class SendMailExample {
public void sendMail(String smtpHost,String username,
String password,String senderAddress,
String recipientsAddress,String subject,String text ) {
MailAuthenticator auth = new MailAuthenticator(username, password);
Properties properties = new Properties();
properties.put("mail.smtp.host", smtpHost);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.starttls.enable", "true");//fix error: 530 5.7.0 Must issue a STARTTLS command first
Session session = Session.getDefaultInstance(properties, auth);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipientsAddress, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("Test", "Test");
msg.setSentDate(new Date( ));
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace( );
}
}
public static void main(String[] args) {
String username = "nick";//nick no @yahoo.com or @gmail.com
String password = "password";//password
String senderAddress ="tronghiencao@gmail.com";//someone@web.com
String recipientsAddress = "caotronghien@yahoo.com"; //somereceiver@yahoo.de
String subject = "Test";
String text = "text";
String smtpHost = "smtp.gmail.com";
new SendMailExample().sendMail(smtpHost, username, password, senderAddress, recipientsAddress, subject, text);
}
}
2 Responses to "Send mail dùng SMTP"
Đăng nhận xét