0

A simple secure MIME message SendMail function

Here is a simple secure MIME message sendMail function;


public boolean sendMail(String to, String subject, String text) {

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", Constants.SMTP_HOST_NAME);
props.put("mail.smtp.port", Constants.SMTP_HOST_PORT);
props.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();

Session mailSession = Session.getInstance(props, auth);

try{
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(Constants.SMTP_MESSAGE_SENDER));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
message.setHeader("MIM9
message.setHeader("Content-Type", "text/html");
message.setContent(text, "text/html");

transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
return true;
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
return false;
} catch (Exception exception){
exception.printStackTrace();
return false;
}


}

private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = Constants.SMTP_AUTH_USER;
String password = Constants.SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}

|

0 Comments

Copyright © 2009 So That I Can Remember All rights reserved. Theme by Laptop Geek. | Bloggerized by FalconHive.