package com.blogspot.na5cent; import java.io.File; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; import javax.mail.internet.MimeMessage; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; public class EmailSender { private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final String SMTP_AUTH_USER = "SENDER_EMAIL"; private static final String SMTP_AUTH_PWD = "SENDER_PASSWORD"; private static final String emailTarget = "RECEIVER_EMAIL"; private static final String emailSubject = "test send email"; private static final String emailFromAddress = "SENDER_EMAIL"; private static final String emailMessage = "test!!!"; public static void main(String args[]) throws Exception { MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); JavaMailSenderImpl sender = new JavaMailSenderImpl(); Properties pro = new Properties(); // pro.setProperty("mail.smtps.host", SMTP_HOST_NAME); // pro.setProperty("mail.smtp.port", "465"); pro.setProperty("mail.smtps.auth", "true"); pro.setProperty("mail.smtps.starttls.enable", "true"); pro.setProperty("mail.debug", "true"); sender.setJavaMailProperties(pro); sender.setUsername(SMTP_AUTH_USER); sender.setPassword(SMTP_AUTH_PWD); sender.setProtocol("smtps"); sender.setPort(465); sender.setHost(SMTP_HOST_NAME); sender.setDefaultEncoding("utf-8"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setSubject(emailSubject); helper.setFrom(emailFromAddress); helper.setText(emailMessage); File part = new File("c:\\temp\\"); //ส่งไฟล์ภาพไปด้วย FileSystemResource file = new FileSystemResource(new File(part, "Koala.jpg")); helper.addAttachment("Koala.jpg", file); helper.setTo(emailTarget); sender.send(message); } }เรามาลองเขียนเป็น component email กันดีกว่าครับ
1. ให้เพิ่ม config ต่อไปนี้ลงใน applicationContext.xml ของ spring framework
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com"/> <property name="port" value="465"/> <property name="protocol" value="smtps"/> <property name="username" value="YOUR_EMAIL_SENDING"/> <property name="password" value="YOUR_PASSWORD_SENDING"/> <property name="defaultEncoding" value="UTF-8"/> <property name="javaMailProperties"> <props> <prop key="mail.smtps.auth">true</prop> <prop key="mail.smtps.starttls.enable">true</prop> <prop key="mail.debug">true</prop> </props> </property> </bean> </beans>2. เขียน component Email
package com.blogspot.na5cent.email; import java.util.List; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import th.co.geniustree.nhso.deficientdrugs.forum.model.UserForum; import th.co.geniustree.nhso.deficientdrugs.forum.repository.UserForumRepo; /** * * @author Redcrow */ @Component public class ForgetPasswordEmail { static { MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); } @Autowired //เป็นการเรียกใช้งาน config file email ใน applicationContext.xml private JavaMailSenderImpl mailSender; @Autowired //ใช้งาน database private UserForumRepo userForumRepo; public boolean send(String userName) { boolean success = false; try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); List<UserForum> users = userForumRepo.findByUserName(userName); if (users.size() != 1) { return false; } UserForum user = users.get(0); helper.setTo(user.getEmail()); helper.setSubject("แจ้งรหัสผ่าน"); helper.setText("ผู้ใช้ : " + user.getFullName() + "<br/>UserName : " + user.getUserName() + "<br/>Password : " + user.getPassword(), true); mailSender.send(message); success = true; } catch (Exception ex) { success = false; } finally { return success; } } }3. การเรียกใช้งาน (ผ่าน JSF Managed Bean)
@ManagedBean @RequestScoped public class ForgetPasswordMB { private static final Logger LOG = LoggerFactory.getLogger(ForgetPasswordMB.class); private String userName; private ForgetPasswordEmail email; @PostConstruct public void postConstruct() { email = JSFSpringUtils.getBean(ForgetPasswordEmail.class); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public void onSendEmail() { if (email.send(userName)) { Notifications.message(Notifications.INFO, "ส่งรหัสผ่านเข้า email ของผู้ใช้", "เรียบร้อย"); } else { Notifications.message(Notifications.WARN, "ส่งรหัสผ่านเข้า email ของผู้ใช้", "ล้มเหลว"); } } }
เราสามารถสร้าง template email สวยๆได้ ซึ่งในที่นี้ผมจะใช้ FreeMarker template engine เข้ามาช่วยครับ อยากได้สวยแค่ไหน ยังไงก็ขึ้นอยู่กับความ Art ของแต่ละคนครับ
เรียนรู้ได้ในหัวข้อ สร้าง template email ด้วย freemarker template engine : java
ไม่มีความคิดเห็น:
แสดงความคิดเห็น