之前都有寫過利用C# , PowerShell 及Java 的 MimeMessage 去傳送電郵. 在此利用Sprint 去發出電郵. 方法如下.
- 建立 application.properties 並輸入以下內容.
# SMTP Settings. spring.mail.host=smtp.office365.com spring.mail.username=<<User Name>> spring.mail.password=<<Password>> spring.mail.properties.mail.transport.protocol=smtp spring.mail.properties.mail.smtp.port=587 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
- 建立 MailController.java 並輸入以下內容.
import java.util.List; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.util.CollectionUtils; import com.microsoft.sqlserver.jdbc.StringUtils; @Controller public class MailController { @Autowired private JavaMailSender sender; private static String EMAIL_FROM_ADDRESS="[email protected]"; public boolean sendEmail(String toAddress, String subject, String body) throws Exception { return this.sendEmail(toAddress, subject, body, StringUtils.EMPTY, null); } public boolean sendEmail(String toAddress, String subject, String body, String ccAddress) throws Exception { return this.sendEmail(toAddress, subject, body, ccAddress, null); } public boolean sendEmail(String toAddress, String subject, String body, String ccAddress, List<ClassPathResource> attachments) throws Exception { boolean result = false; try { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(EMAIL_FROM_ADDRESS); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress)); helper.setSubject(subject); helper.setText(body, true); if (StringUtils.isEmpty(ccAddress) == false) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddress)); if (CollectionUtils.isEmpty(attachments) == false) { attachments.forEach(attachment -> { try { helper.addAttachment(attachment.getFilename(), attachment); } catch (Exception ex) { ex.printStackTrace(); } }); } sender.send(message); result = true; } catch (Exception ex) { throw (ex); } return result; } }
Leave a Reply