1. 程式人生 > 其它 >JAVA中傳送郵件

JAVA中傳送郵件

1.匯入需要資源JAR包

<!-- 匯入操作郵件的jar -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

 2.獲取郵箱的授權碼,郵箱客戶端,在設定中可以獲得

  我使用網易郵箱,登入網易郵箱後在設定中的 POP3/SMTP/IMAP 選項中找到授權密碼管理,如下圖

  

3.編寫程式碼如下

public class MailAuthenticator extends Authenticator {
    //發件者郵箱
    public static String USERNAME= "[email protected]";
    //郵箱授權碼
    public static String PASSWORD= "這裡是郵箱的授權碼";

    public MailAuthenticator(){}

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(USERNAME, PASSWORD);
    }
}
public class MailOperation {

    /**
     *
     * @param user          發件人郵箱
     * @param password      password授權碼
     * @param host          host
     * @param from          發件人
     * @param to            接收者郵箱
     * @param subject       郵件主題
     * @param content       郵件內容
     * @return              success傳送成功, failure 傳送失敗
     * @throws Exception
     */
    public String sendMail(String user, String password, String host, String from, String to, String subject, String content) throws Exception {
        if (to != null){
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            MailAuthenticator auth = new MailAuthenticator();
            MailAuthenticator.USERNAME = user;
            MailAuthenticator.PASSWORD = password;
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            try {
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                if (!to.trim().equals("")){
                    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to.trim()));
                }
                message.setSubject(subject);
                // 正文
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setContent(content, "text/html;charset=utf-8");
                // 整個郵件:正文+附件
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);
                message.setContent(mp);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport trans = session.getTransport("smtp");
                Transport.send(message);
                System.out.println(message.toString());
            } catch (Exception e){
                e.printStackTrace();
                return "failure";
            }
            return "success";
        }else{
            return "failure";
        }
    }

  

測試程式碼

 public static void main(String[] args) {
        MailOperation operation = new MailOperation();
        String user = "[email protected]";
        String password = "這裡是拿到的郵箱授權碼";
        String host = "smtp.163.com";
        String from = "[email protected]";
        //收件人
        String to = "[email protected]";
        String subject = "這裡是郵件的主題";
        //郵箱內容
        StringBuffer sb = new StringBuffer();
        String yzm = RandomUtil.getRandomString(6);
        sb.append("<!DOCTYPE>"+"<div bgcolor='#f1fcfa'   style='border:1px solid #d9f4ee; font-size:14px; line-height:22px; color:#005aa0;padding-left:1px;padding-top:5px;   padding-bottom:5px;'><span style='font-weight:bold;'>溫馨提示:</span>"
                + "<div style='width:950px;font-family:arial;'>歡迎使用*******,您的註冊碼為:<br/><h2 style='color:green'>"+yzm+"</h2><br/>本郵件由系統自動發出,請勿回覆。<br/>感謝您的使用。<br/>xxx電子商務有限公司</div>"
                +"</div>");
        try {
            String res = operation.sendMail(user, password, host, from, to,
                    subject, sb.toString());
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

  

如有錯誤,請指正! 聯絡wx 15514769010