Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Properties;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- public class SimpleEmail {
- public String smtpHostname;
- public String smtpPort;
- public String smtpUser;
- public String smtpPassword;
- public String fromAddress;
- public String toAddress;
- public String useTLS = "false";
- public String useAuthentication = "true";
- public static void main(String[] args) throws Exception{
- SimpleEmail mail01 = new SimpleEmail();
- mail01.smtpHostname = "smtpservername";
- mail01.smtpPort = "587";
- mail01.fromAddress = "email@example.org";
- mail01.smtpUser = "domain\\username";
- mail01.smtpPassword = "password";
- mail01.toAddress = "email@example.org";
- mail01.sendEmail();
- }
- public void sendEmail() throws Exception{
- // TODO check if all properties where set
- Properties props = new Properties();
- props.setProperty("mail.transport.protocol", "smtp");
- props.setProperty("mail.smtp.port", smtpPort);
- props.setProperty("mail.smtp.starttls.enable", useTLS);
- props.setProperty("mail.smtp.host", smtpHostname);
- props.setProperty("mail.smtp.auth", useAuthentication);
- Authenticator auth = new SMTPAuthenticator();
- Session mailSession = Session.getDefaultInstance(props, auth);
- // uncomment for debugging infos to stdout
- // mailSession.setDebug(true);
- Transport transport = mailSession.getTransport();
- MimeMessage message = new MimeMessage(mailSession);
- message.setContent("This is a test", "text/plain");
- message.setFrom(new InternetAddress(fromAddress));
- message.addRecipient(Message.RecipientType.TO,
- new InternetAddress(toAddress));
- transport.connect();
- transport.sendMessage(message,
- message.getRecipients(Message.RecipientType.TO));
- transport.close();
- }
- private class SMTPAuthenticator extends Authenticator {
- public PasswordAuthentication getPasswordAuthentication() {
- String username = smtpUser;
- String password = smtpPassword;
- return new PasswordAuthentication(username, password);
- }
- }
- }
Add Comment
Please, Sign In to add comment