Created
February 4, 2011 10:09
-
-
Save mwanji/810948 to your computer and use it in GitHub Desktop.
An example API to rival Groovy's mail API
Cf. https://groups.google.com/d/msg/lescastcodeurs/TRONQ4Mo-fE/hKhnr6gMuyMJ for context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.moandjiezana.mailapi; | |
import java.util.Date; | |
import java.util.Properties; | |
import javax.mail.Message.RecipientType; | |
import javax.mail.MessagingException; | |
import javax.mail.Session; | |
import javax.mail.Transport; | |
import javax.mail.internet.AddressException; | |
import javax.mail.internet.InternetAddress; | |
import javax.mail.internet.MimeMessage; | |
public class MailBuilder { | |
private String from; | |
private String to; | |
private String subject; | |
private String body; | |
public static MailBuilder from(String email) { | |
return new MailBuilder(email); | |
} | |
public MailBuilder to(String... to) { | |
for (String to1 : to) { | |
this.to += to1 + ";"; | |
} | |
return this; | |
} | |
public MailBuilder subject(String subject) { | |
this.subject = subject; | |
return this; | |
} | |
public MailBuilder body(String body) { | |
this.body = body; | |
return this; | |
} | |
public void send() { | |
Properties properties = new Properties(); | |
Session session = Session.getDefaultInstance(properties); | |
MimeMessage message = new MimeMessage(session); | |
try { | |
message.setFrom(new InternetAddress(from)); | |
message.setRecipients(RecipientType.TO, InternetAddress.parse(to)); | |
message.setSubject(subject); | |
message.setText(body); | |
message.setSentDate(new Date()); | |
Transport.send(message); | |
} catch (AddressException e) { | |
throw new RuntimeException(e); | |
} catch (MessagingException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private MailBuilder(String from) { | |
this.from = from; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment