Java App: Send SMTP Mail Example

การส่งเมล์โดยใช้ java สามารถใช้ class ใน javax.mail ได้ ซึ่งตัวอย่างข้างล่างเป็น utility ที่สามารถเรียกใช้ได้เลย

MailUtility.java

package com.amadmonster.util.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
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;

import org.apache.log4j.Logger;

public class MailUtility {
/** Get logger. */
private static Logger logger = Logger.getLogger(MailUtility.class);
Properties props;

public MailUtility(String smtpServer) {
props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
}

public void sendMail(String to, String from, String subject, String body) throws MailUtilityException {
Session session = Session.getDefaultInstance(props);
session.setDebug(false);

Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, true));
msg.setSubject(subject);
// check mime type from Web: Content Type
msg.setContent(body, "text/plain");
msg.setText(body);
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
logger.info("Message sent OK.");

} catch (AddressException e) {
throw new MailUtilityException("Incorrrect address format", e);
} catch (MessagingException e) {
throw new MailUtilityException("Error occurs when sending mail", e);
}

}
}

MailUtilityException.java


package com.amadmonster.util.mail;

public class MailUtilityException extends Exception {

public MailUtilityException(String message, Throwable cause) {
super(message, cause);
}

public MailUtilityException(String message) {
super(message);
}

public MailUtilityException(Throwable cause) {
super(cause);
}

}


Reference:
JavaMail quick start

No comments:

Post a Comment