【工具类】发送邮件的方法
生活随笔
收集整理的這篇文章主要介紹了
【工具类】发送邮件的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
依賴
<!--javaMail--><dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId><version>1.5.6</version></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.5.3</version></dependency>封裝好的工具類
package cs.wy.travel.util;import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties;/*** 發郵件工具類*/ public final class MailUtils {private static final String USER = "66666666@qq.com"; // 發件人稱號,同郵箱地址private static final String PASSWORD = "dhasjkdhaks"; // 如果是qq郵箱可以使戶端授權碼,或者登錄密碼/**** @param to 收件人郵箱* @param text 郵件正文* @param title 標題*//* 發送驗證信息的郵件 */public static boolean sendMail(String to, String text, String title){try {final Properties props = new Properties();props.put("mail.smtp.auth", "true");props.put("mail.smtp.host", "smtp.qq.com");// 發件人的賬號props.put("mail.user", USER);//發件人的密碼props.put("mail.password", PASSWORD);// 構建授權信息,用于進行SMTP進行身份驗證Authenticator authenticator = new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {// 用戶名、密碼String userName = props.getProperty("mail.user");String password = props.getProperty("mail.password");return new PasswordAuthentication(userName, password);}};// 使用環境屬性和授權信息,創建郵件會話Session mailSession = Session.getInstance(props, authenticator);// 創建郵件消息MimeMessage message = new MimeMessage(mailSession);// 設置發件人String username = props.getProperty("mail.user");InternetAddress form = new InternetAddress(username);message.setFrom(form);// 設置收件人InternetAddress toAddress = new InternetAddress(to);message.setRecipient(Message.RecipientType.TO, toAddress);// 設置郵件標題message.setSubject(title);// 設置郵件的內容體message.setContent(text, "text/html;charset=UTF-8");// 發送郵件Transport.send(message);return true;}catch (Exception e){e.printStackTrace();}return false;}public static void main(String[] args) throws Exception { // 做測試用MailUtils.sendMail("88888888@qq.com","你好,這是一封測試郵件,無需回復。","測試郵件");System.out.println("發送成功");} }測試結果
總結
以上是生活随笔為你收集整理的【工具类】发送邮件的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【SSM框架系列】SpringMVC基本
- 下一篇: 【工具类】加密工具---MD5使用