package cn.aprilsoft.mail;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import cn.aprilsoft.lang.StringUtil;
public class Mailer {
private String smtp;
private String from;
private String username;
private String password;
protected Mailer(String smtp, String from, String username, String password) {
this.smtp = smtp;
this.from = from;
this.username = username;
this.password = password;
}
public static Mailer create(String smtp, String from, String username, String password) {
return new Mailer(smtp, from, username, password);
}
public Mailer password(String password) {
this.password = password;
return this;
}
public void send(String to, String subject, String body) {
send(to, null, null, subject, body);
}
public void send(String to, String cc, String bcc, String subject, String body) {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.calss", "com.sun.mail.smtp.SMTPTransport");
props.put("mail.smtp.host", smtp);
props.put("mail.smtp.auth", "true");
MailAuthenticator auth = new MailAuthenticator();
auth.check(username, password);
Session mailsession = Session.getDefaultInstance(props, auth);
Message message = new MimeMessage(mailsession);
try {
InternetAddress[] toAddress = InternetAddress.parse(to);
message.setRecipients(Message.RecipientType.TO, toAddress);
if (StringUtil.isNotEmpty(cc)) {
InternetAddress[] ccAddress = InternetAddress.parse(cc);
message.setRecipients(Message.RecipientType.CC, ccAddress);
}
if (StringUtil.isNotEmpty(bcc)) {
InternetAddress[] bccAddress = InternetAddress.parse(bcc);
message.setRecipients(Message.RecipientType.BCC, bccAddress);
}
message.addHeader("X-Mailer-Sender", "TinyAppServer/1.0 JSSP/1.0 Mailer/1.0");
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.setText(body);
Transport.send(message);
} catch (Exception ex) {
throw new MailerException(ex);
}
}
}