Skip to content

Instantly share code, notes, and snippets.

@kazmura11
Last active August 29, 2015 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazmura11/10560342 to your computer and use it in GitHub Desktop.
Save kazmura11/10560342 to your computer and use it in GitHub Desktop.
package mail;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPTransport;
public class MailSender {
// Constants
private static final String MAIL_PROPERTIES = "resources.mail";
private static final String PROP_PROTOCOL = "smtp";
private static final String PROP_HOST = "mail.host";
private static final String PROP_SMTP_HOST = "mail.smtp.host";
private static final String PROP_SMTP_PORT = "mail.smtp.port";
private static final String PROP_SMTP_AUTH = "mail.smtp.auth";
private static final String PROP_SMTP_STARTTLS = "mail.smtp.starttls.enable";
private static final String PROP_ENCODING = "mail.encoding";
private static final String PROP_TEMPLATE_ENCODING = "mail.template.encoding";
private static final String DEFAULT_ENCODING = "ISO-2022-JP";
private static final String DEFAULT_TEMPLATE_ENCODING = "UTF-8";
// Fields
private String host = null;
private String smtpHost = null;
private String smtpPort = null;
private String smtpAuth = null;
private String smtpStartTls = null;
private String from = null;
private String fromName = null;
private String account = null;
private String password = null;
private List<String> toList = new ArrayList<String>();
private List<String> ccList = new ArrayList<String>();
private List<String> bccList = new ArrayList<String>();
private String subject = null;
private String mailContent = null;
private String encoding = null;
private String templateEncoding = null;
private static ResourceBundle bundle = null;
static {
try {
// read Property File
bundle = ResourceBundle.getBundle(MAIL_PROPERTIES);
} catch (Throwable t) {
t.printStackTrace();
}
}
// Constructor
public MailSender() {
// read property file and set parameter
if (bundle.containsKey(PROP_HOST)) {
host = bundle.getString(PROP_HOST);
}
if (bundle.containsKey(PROP_SMTP_HOST)) {
smtpHost = bundle.getString(PROP_SMTP_HOST);
}
if (bundle.containsKey(PROP_SMTP_PORT)) {
smtpPort = bundle.getString(PROP_SMTP_PORT);
}
if (bundle.containsKey(PROP_SMTP_AUTH)) {
smtpAuth = bundle.getString(PROP_SMTP_AUTH);
}
if (bundle.containsKey(PROP_SMTP_STARTTLS)) {
smtpStartTls = bundle.getString(PROP_SMTP_STARTTLS);
}
if (bundle.containsKey(PROP_ENCODING)) {
encoding = bundle.getString(PROP_ENCODING);
}
else {
encoding = DEFAULT_ENCODING;
}
if (bundle.containsKey(PROP_TEMPLATE_ENCODING)) {
templateEncoding = bundle.getString(PROP_TEMPLATE_ENCODING);
}
else {
templateEncoding = DEFAULT_TEMPLATE_ENCODING;
}
}
// Function
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return this.host;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpHost() {
return this.smtpHost;
}
public void setSmtpPort(String smtpPort) {
this.smtpPort = smtpPort;
}
public String getSmtpPort() {
return this.smtpPort;
}
public void setSmtpAuth(String smtpAuth) {
this.smtpAuth = smtpAuth;
}
public String getSmtpAuth() {
return this.smtpAuth;
}
public void setSmtpStarTls(String smtpStartTls) {
this.smtpStartTls = smtpStartTls;
}
public String getSmtpStartTls() {
return this.smtpStartTls;
}
public void setFromAddress(String from) {
this.from = from;
}
public String getFromAddress() {
return this.from;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getFromName() {
return this.fromName;
}
public void setAccount(String account) {
this.account = account;
}
public String getAccount() {
return this.account;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassowrd() {
return this.password;
}
public void addToAddress(String toAddress) {
toList.add(toAddress);
}
public void addToAddress(List<String> toAddressList) {
toList.addAll(toAddressList);
}
public List<String> getToAddress() {
return toList;
}
public void addCcAddress(String ccAddress) {
ccList.add(ccAddress);
}
public void addCcAddress(List<String> ccAddressList) {
ccList.addAll(ccAddressList);
}
public List<String> getCcAddress() {
return ccList;
}
public void addBccAddress(String bccAddress) {
bccList.add(bccAddress);
}
public void addBccAddress(List<String> bccAddressList) {
bccList.addAll(bccAddressList);
}
public List<String> getBccAddress() {
return bccList;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
public void setMailContent(String mailContent) {
this.mailContent = mailContent;
}
public String getMailContent() {
return mailContent;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding() {
return encoding;
}
public void setTemplateEncoding(String templateEncoding) {
this.templateEncoding = templateEncoding;
}
public String getTemplateEncoding() {
return templateEncoding;
}
private String readTemplate(String id) throws IOException {
String path = null;
if (bundle.containsKey(id)) {
path = bundle.getString(id);
}
if (path == null || path.trim().length() == 0) {
throw new IllegalArgumentException(
"Path of mail template["+id+"] is not found in mail.properties");
}
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
StringBuilder sb = null;
try {
// Use InputStream to set file encoding
fis = new FileInputStream(path);
isr = new InputStreamReader(fis, templateEncoding);
br = new BufferedReader(isr);
sb = new StringBuilder();
for (String line = null; (line = br.readLine()) != null; ) {
sb.append(line);
sb.append("\r\n");
}
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public void setMailContentFromTemplate(String id) throws IOException {
this.mailContent = readTemplate(id);
}
public void replaceMailContent(String regex, String replacement) {
this.mailContent = this.mailContent.replaceAll(regex, replacement);
}
public void send() throws MessagingException, UnsupportedEncodingException {
if (smtpHost == null) {
throw new IllegalArgumentException("Mail server Hostname or ip address is empty.");
}
if (toList.size() == 0) {
throw new IllegalArgumentException("To address is not set");
}
if (from == null) {
throw new IllegalArgumentException("From address is not set");
}
// smtp settings
Properties props = new Properties();
props.setProperty(PROP_HOST, host);
props.setProperty(PROP_SMTP_HOST, smtpHost);
props.setProperty(PROP_SMTP_PORT, smtpPort);
props.setProperty(PROP_SMTP_AUTH, smtpAuth);
props.setProperty(PROP_SMTP_STARTTLS, smtpStartTls);
Session session = Session.getInstance(props);
MimeMessage msg = new MimeMessage(session);
InternetAddress[] toAddressArray = new InternetAddress[toList.size()];
for (int i = 0; i < toList.size(); i ++) {
toAddressArray[i] = new InternetAddress(toList.get(i));
}
msg.setRecipients(Message.RecipientType.TO, toAddressArray);
if (ccList.size() > 0) {
InternetAddress[] ccAddressArray = new InternetAddress[ccList.size()];
for (int i = 0; i < ccList.size(); i ++) {
ccAddressArray[i] = new InternetAddress(ccList.get(i));
}
msg.setRecipients(Message.RecipientType.CC, ccAddressArray);
}
if (bccList.size() > 0) {
InternetAddress[] bccAddressArray = new InternetAddress[bccList.size()];
for (int i = 0; i < bccList.size(); i ++) {
bccAddressArray[i] = new InternetAddress(bccList.get(i));
}
msg.setRecipients(Message.RecipientType.BCC, bccAddressArray);
}
InternetAddress addrFrom = null;
if (fromName != null) {
addrFrom = new InternetAddress(from, fromName, encoding);
} else {
addrFrom = new InternetAddress(from);
}
msg.setFrom(addrFrom);
msg.setSubject(subject, encoding);
msg.setText(mailContent, encoding);
// 画像を添付したい場合は下記のソースを参考にすると良い
//Multipart mp = new MimeMultipart();
//MimeBodyPart mbp1 = new MimeBodyPart();
//mbp1.setText(mailContent, encoding);
//mbp1.setHeader("Content-Type","text/plain");
//mp.addBodyPart(mbp1);
//// add image files
//DataHandler imgdh = null;
//FileDataSource fds = new FileDataSource(filename));
//imgdh = new DataHandler(fds);
//MimeBodyPart mbp2 = new MimeBodyPart();
//mbp2.setDataHandler(imgdh);
//mbp2.setFileName(MimeUtility.encodeWord(filename));
//mp.addBodyPart(mbp2);
//msg.setContent(mp);
msg.setSentDate(new java.util.Date());
SMTPTransport t = (SMTPTransport) session.getTransport(PROP_PROTOCOL);
try {
t.connect(smtpHost, account, password);
t.sendMessage(msg, msg.getAllRecipients());
}
finally {
t.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment