Skip to content

Instantly share code, notes, and snippets.

@amolbrid
Created February 16, 2011 04:54
Show Gist options
  • Save amolbrid/828893 to your computer and use it in GitHub Desktop.
Save amolbrid/828893 to your computer and use it in GitHub Desktop.
Send email in java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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 Mailer {
private Properties mailSettings;
public Mailer() throws IOException {
InputStream is = null;
try {
is = this.getClass().getClassLoader().getResourceAsStream("mail.properties");
mailSettings = new Properties();
mailSettings.load(is);
mailSettings.put("mail.smtp.auth", "true");
mailSettings.put("mail.transport.protocol", "smtp");
} finally {
try {
if(is != null) { is.close(); }
} catch(IOException e) {}
}
}
public void send(String content) throws AddressException, MessagingException {
Session session = Session.getDefaultInstance(mailSettings, new SMTPAuthenticator());
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailSettings.getProperty("from")));
message.addRecipients(Message.RecipientType.TO, getRecipients());
message.setSubject("Test mail from java");
message.setText("This is a test mail.");
Transport.send(message);
}
private Address[] getRecipients() throws AddressException {
String recipients = mailSettings.getProperty("to");
String[] emails = recipients.split(",");
Address[] emailAddress = new InternetAddress[emails.length];
int index = 0;
for(String email : emails) {
emailAddress[index++] = new InternetAddress(email);
}
return emailAddress;
}
private class SMTPAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailSettings.getProperty("username"),
mailSettings.getProperty("password"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment