使用javaMail實現簡單郵件發送


一、首先你要用來發送郵件的qq郵箱需要開通pop3/smtp服務,這個可以百度一下就知道了

二、導入所需要的jar包,我使用的是maven添加依賴

<dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1.1</version>
</dependency>
<dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.7</version>
</dependency>
<dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>smtp</artifactId>
      <version>1.6.0</version>
</dependency>

三、進行工具類編寫並測試,代碼如下

package com.cccuu.project.myUtils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/******************************************* 
 *  使用smtp協議發送郵件
 * @Package com.cccuu.project.myUtils
 * @Author drt
 * @Date 2018/3/28 11:40
 * @Version V1.0
 *******************************************/
public class JavaMailUtil {

    private final static String PROTOCOL = "smtp";  // 郵件發送協議
    private final static String HOST = "smtp.qq.com"; //郵件服務器主機
    private final static String PORT = "465";    // SMTP郵件服務器默認端口
    private final static String IS_AUTH = "true";  // 是否要求身份認證
    private final static String IS_ENABLED_DEBUG_MOD = "true";  //// 是否啟用調試模式(啟用調試模式可打印客戶端與服務器交互過程時一問一答的響應消息)

    // 初始化連接郵件服務器的會話信息
    private static Properties props = null;

    static {
        props = new Properties();
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", IS_AUTH);
        props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
    }

    /**
     * 發送郵件工具類:通過qq郵件發送,因為具有ssl加密,采用的是smtp協議
     * @param loginAccount 登錄郵箱的賬號:如 "1576357208@qq.com"
     * @param loginAuthCode 登錄qq郵箱時候需要的授權碼:可以進入qq郵箱,賬號設置那里"生成授權碼"
     * @param sender 發件人郵箱
     * @param recipients 收件人郵箱:支持群發
     * @param emailSubject 郵件的主題
     * @param emailContent 郵件的內容
     * @param emailContentType 郵件內容的類型,支持純文本:"text/plain;charset=utf-8";,帶有Html格式的內容:"text/html;charset=utf-8"
     * @return 是否成功
     */
    public static boolean sendEmail(final String loginAccount,final String loginAuthCode,String sender,String[] recipients,
                                String emailSubject,String emailContent,String emailContentType){
        boolean flag;
        try {
            //開啟SSL加密,否則會失敗
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
            // 創建session
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    //用戶名可以用QQ賬號也可以用郵箱的別名:第一個參數為郵箱賬號,第二個為授權碼
                    PasswordAuthentication pa = new PasswordAuthentication(loginAccount,loginAuthCode);
                    return pa;
                }
            });
            //設置打開調試狀態
            //session.setDebug(true);
            //聲明一個Message對象(代表一封郵件),從session中創建,可以發送幾封郵件:可以在這里 for循環多次
            MimeMessage msg = new MimeMessage(session);
            //郵件信息封裝
            //1發件人
            msg.setFrom(new InternetAddress(sender));
            //2收件人:可以多個
            //msg.setRecipient(RecipientType.TO, new InternetAddress("linsenzhong@126.com"));
            InternetAddress[] receptientsEmail=new InternetAddress[recipients.length];
            for(int i=0;i<recipients.length;i++){
                receptientsEmail[i]=new InternetAddress(recipients[i]);
            }
            //多個收件人
            msg.setRecipients(RecipientType.TO,receptientsEmail);
            //設置發送時間
            msg.setSentDate(new Date());
            //設置郵件優先級
            msg.setHeader("X-Priority","1");
            //3郵件內容:主題、內容
            msg.setSubject(emailSubject);
            //設置html內容為郵件正文
            msg.setContent(emailContent,emailContentType);
            //設置自定義發件人昵稱
            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText("河南靈秀網絡科技有限公司");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            msg.setFrom(new InternetAddress(nick+" <"+sender+">"));
            // 保存並生成最終的郵件內容
            msg.saveChanges();
            //發送動作
            Transport.send(msg);
            System.out.println("郵件發送成功");
            flag=true;

        } catch (Exception e) {
            System.out.println("郵件發送失敗: "+e.getMessage());
            flag=false;
        }
        return flag;
    }

    public static void main(String[] args) throws Exception {
        String code=UUID.randomUUID().toString();
        boolean result=sendEmail("1576357208@qq.com", "lisaygkznttogjhj", "1576357208@qq.com",
                new String[]{"17737138812@163.com","303157545@qq.com"},
                "修改密碼驗證碼",
                "<h3 style='margin-left: 10px; color: #00a0e9'>你的驗證碼是"+code+",10分鍾內有效,過期請重新獲取</h3>",
                "text/html;charset=utf-8");
        System.out.println("\n發送結果:"+result);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM