Skip to content

Instantly share code, notes, and snippets.

@froop
Created February 16, 2012 14:41
Show Gist options
  • Save froop/1845346 to your computer and use it in GitHub Desktop.
Save froop/1845346 to your computer and use it in GitHub Desktop.
[Java] メール送信(単一メール・複数BCC宛先)
import javax.mail.*;
public class MailSender {
private final Properties props = loadProperties("/mail/MailSender.properties");
private final Session session = createSession();
private Properties loadProperties(String propPath) {
try {
Properties res = new Properties();
res.load(MailSender.class.getResourceAsStream(propPath));
return res;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Session createSession() {
Session res = Session.getDefaultInstance(props);
res.setDebug(Boolean.valueOf(props.getProperty("session.debug")));
return res;
}
public void sendBcc(List<String> addresses, String subject, String body) {
try {
MimeMessage message = createBccMessage(addresses, subject, body);
sendMessage(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private MimeMessage createBccMessage(List<String> bcc, String subject,
String body) throws MessagingException {
MimeMessage message = createMessage(subject, body);
Address[] bccArray = toAddressArray(bcc);
message.setRecipients(Message.RecipientType.BCC, bccArray);
return message;
}
private MimeMessage createMessage(String subject, String body)
throws MessagingException {
MimeMessage message = new MimeMessage(session);
String charset = props.getProperty("message.charset");
message.setSubject(subject, charset);
message.setText(body, charset);
return message;
}
private Address[] toAddressArray(List<String> stringList)
throws AddressException {
List<Address> addressList = new ArrayList<Address>();
for (String item : stringList) {
addressList.add(new InternetAddress(item));
}
return addressList.toArray(new Address[0]);
}
private void sendMessage(MimeMessage message)
throws MessagingException {
Transport transport = session.getTransport("smtp");
String user = props.getProperty("transport.user");
String password = props.getProperty("transport.password");
transport.connect(user, password);
try {
transport.sendMessage(message, message.getAllRecipients());
} finally {
transport.close();
}
}
}
# JavaMail API
mail.smtp.host=smtp.gmail.com
mail.smtp.port=587
mail.smtp.auth=true
mail.smtp.starttls.enable=true
[email protected]
# dedicated
[email protected]
transport.password=xxxxxxxx
message.charset=ISO-2022-JP
session.debug=true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment