如何使用java來發(fā)送郵件

這篇文章主要介紹了如何使用java來發(fā)送郵件的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇如何使用java來發(fā)送郵件文章都會(huì)有所收獲,下面我們一起來看看吧。

創(chuàng)新互聯(lián)建站-云計(jì)算及IDC服務(wù)提供商,涵蓋公有云、IDC機(jī)房租用、托管服務(wù)器、等保安全、私有云建設(shè)等企業(yè)級(jí)互聯(lián)網(wǎng)基礎(chǔ)服務(wù),聯(lián)系電話:028-86922220

首先看一下實(shí)現(xiàn)的步驟,然后在講講有可能遇到的問題

1.引入javax.mail依賴,我用的是springboot,所以依賴是這樣引的

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

沒用springboot框架的,自己去找一下

2.構(gòu)建郵件基本信息類

package com.example.demo.comment.sendemail;

import java.util.Properties;

/**
 * 發(fā)送郵件需要使用的基本信息
 *
 * @author 860118060
 */
public class MailSenderInfo {
    /**
     * 發(fā)送郵件的服務(wù)器的IP和端口
     */
    private String mailServerHost;
    private String mailServerPort = "25";
    /**
     * 郵件發(fā)送者的地址
     */
    private String fromAddress;
    /**
     * 郵件接收者的地址
     */
    private String toAddress;
    /**
     * 登陸郵件發(fā)送服務(wù)器的用戶名和密碼
     */
    private String userName;
    private String password;
    /**
     * 是否需要身份驗(yàn)證
     */
    private boolean validate = false;
    /**
     * 郵件主題
     */
    private String subject;
    /**
     * 郵件的文本內(nèi)容
     */
    private String content;
    /**
     * 郵件附件的文件名
     */
    private String[] attachFileNames;

    /**
     * 獲得郵件會(huì)話屬性
     */
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return mailServerHost;
    }

    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }

    public String getMailServerPort() {
        return mailServerPort;
    }

    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String[] getAttachFileNames() {
        return attachFileNames;
    }

    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String textContent) {
        this.content = textContent;
    }
}

3.構(gòu)建郵件發(fā)送器

package com.example.demo.comment.sendemail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * 簡單郵件(不帶附件的郵件)發(fā)送器
 */
public class SimpleMailSender  {
    /**
     * 以文本格式發(fā)送郵件
     * @param mailInfo 待發(fā)送的郵件的信息
     */
    public static boolean sendTextMail(MailSenderInfo mailInfo) {
        // 判斷是否需要身份認(rèn)證
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份認(rèn)證,則創(chuàng)建一個(gè)密碼驗(yàn)證器
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
        Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
        try {
            // 根據(jù)session創(chuàng)建一個(gè)郵件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 創(chuàng)建郵件發(fā)送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 設(shè)置郵件消息的發(fā)送者
            mailMessage.setFrom(from);
            // 創(chuàng)建郵件的接收者地址,并設(shè)置到郵件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO,to);
            // 設(shè)置郵件消息的主題
            mailMessage.setSubject(mailInfo.getSubject());
            // 設(shè)置郵件消息發(fā)送的時(shí)間
            mailMessage.setSentDate(new Date());
            // 設(shè)置郵件消息的主要內(nèi)容
            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);
            // 發(fā)送郵件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 以HTML格式發(fā)送郵件
     * @param mailInfo 待發(fā)送的郵件信息
     */
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){
        // 判斷是否需要身份認(rèn)證
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        //如果需要身份認(rèn)證,則創(chuàng)建一個(gè)密碼驗(yàn)證器
        if (mailInfo.isValidate()) {
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根據(jù)郵件會(huì)話屬性和密碼驗(yàn)證器構(gòu)造一個(gè)發(fā)送郵件的session
        Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
        try {
            // 根據(jù)session創(chuàng)建一個(gè)郵件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 創(chuàng)建郵件發(fā)送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 設(shè)置郵件消息的發(fā)送者
            mailMessage.setFrom(from);
            // 創(chuàng)建郵件的接收者地址,并設(shè)置到郵件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            // Message.RecipientType.TO屬性表示接收者的類型為TO
            mailMessage.setRecipient(Message.RecipientType.TO,to);
            // 設(shè)置郵件消息的主題
            mailMessage.setSubject(mailInfo.getSubject());
            // 設(shè)置郵件消息發(fā)送的時(shí)間
            mailMessage.setSentDate(new Date());
            // MiniMultipart類是一個(gè)容器類,包含MimeBodyPart類型的對(duì)象
            Multipart mainPart = new MimeMultipart();
            // 創(chuàng)建一個(gè)包含HTML內(nèi)容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 設(shè)置HTML內(nèi)容
            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 將MiniMultipart對(duì)象設(shè)置為郵件內(nèi)容
            mailMessage.setContent(mainPart);
            // 發(fā)送郵件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}

4.構(gòu)建密碼驗(yàn)證器

package com.example.demo.comment.sendemail;
import javax.mail.*;

/**
 * @author 860118060
 */
public class MyAuthenticator extends Authenticator{
    String userName=null;
    String password=null;

    public MyAuthenticator(){
    }
    public MyAuthenticator(String username, String password) {
        this.userName = username;
        this.password = password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName, password);
    }
}

至此準(zhǔn)備工作都完成了,下面看一下如何調(diào)用吧

5.調(diào)用Demo

package com.example.demo.comment.sendemail;

public class SendEmailDemo {
    public static void main(String[] args){
        //這個(gè)類主要是設(shè)置郵件
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost("smtp.163.com");
        mailInfo.setMailServerPort("25");
        mailInfo.setValidate(true);
        // 發(fā)送方郵箱
        mailInfo.setUserName("xxxxxxxx@163.com");
        // 發(fā)送方郵箱密碼
        mailInfo.setPassword("xxxxxxxx");
        // 發(fā)送方郵箱
        mailInfo.setFromAddress("xxxxxxxx@163.com");
        // 接收方郵箱
        mailInfo.setToAddress("xxxxxxxx@qq.com");
        // 郵件標(biāo)題
        mailInfo.setSubject("測(cè)試用郵箱發(fā)送郵件");
        // 郵件內(nèi)容
        mailInfo.setContent("<h2>郵件內(nèi)容非常豐富<h2>");

        //發(fā)送文體格式
        SimpleMailSender.sendTextMail(mailInfo);
        //發(fā)送html格式
        SimpleMailSender.sendHtmlMail(mailInfo);
    }
}

這里有兩種郵件發(fā)送格式

如何使用java來發(fā)送郵件

如何使用java來發(fā)送郵件

問題與總結(jié)

如果不出意外的話應(yīng)該成功發(fā)送出兩封郵件了,但是凡事都有萬一,下面分析一下哪些問題會(huì)導(dǎo)致失敗呢?

1.mailInfo.setMailServerHost("smtp.163.com");與mailInfo.setFromAddress("xxxxxxxx@163.com");這兩句話。即如果你使用163smtp服務(wù)器,那么發(fā)送郵件地址就必須用163的郵箱,如果不的話,是不會(huì)發(fā)送成功的。

2.不要使用你剛剛注冊(cè)過的郵箱在程序中發(fā)郵件,如果你的163郵箱是剛注冊(cè)不久,那你就不要使用“smtp.163.com”。因?yàn)槟惆l(fā)不出去。剛注冊(cè)的郵箱是不會(huì)給你這種權(quán)限的,也就是你不能通過驗(yàn)證。要使用你經(jīng)常用的郵箱,而且時(shí)間比較長的

3.qq郵箱作為發(fā)送方是有可能需要授權(quán)驗(yàn)證的。

授權(quán)如下:
在設(shè)置里面找到賬戶,往下拉找到并按照提示開啟授權(quán),然后將得到的授權(quán)碼作為郵箱密碼,即可成功發(fā)送郵件
如何使用java來發(fā)送郵件

如何使用java來發(fā)送郵件

最后順便附上常用郵箱:

常用的郵箱服務(wù)器(SMTP、POP3)地址、端口

sina.com:
POP3服務(wù)器地址:pop3.sina.com.cn(端口:110) SMTP服務(wù)器地址:smtp.sina.com.cn(端口:25)
sinaVIP:
POP3服務(wù)器:pop3.vip.sina.com (端口:110) SMTP服務(wù)器:smtp.vip.sina.com (端口:25)
sohu.com:
POP3服務(wù)器地址:pop3.sohu.com(端口:110) SMTP服務(wù)器地址:smtp.sohu.com(端口:25)
126郵箱:
POP3服務(wù)器地址:pop.126.com(端口:110) SMTP服務(wù)器地址:smtp.126.com(端口:25)
139郵箱:
POP3服務(wù)器地址:POP.139.com(端口:110) SMTP服務(wù)器地址:SMTP.139.com(端口:25)
163.com:
POP3服務(wù)器地址:pop.163.com(端口:110) SMTP服務(wù)器地址:smtp.163.com(端口:25)
QQ郵箱
POP3服務(wù)器地址:pop.qq.com(端口:110)
SMTP服務(wù)器地址:smtp.qq.com (端口:25)
QQ企業(yè)郵箱
POP3服務(wù)器地址:pop.exmail.qq.com (SSL啟用 端口:995) SMTP服務(wù)器地址:smtp.exmail.qq.com(SSL啟用 端口:587/465)
yahoo.com:
POP3服務(wù)器地址:pop.mail.yahoo.com SMTP服務(wù)器地址:smtp.mail.yahoo.com
yahoo.com.cn:
POP3服務(wù)器地址:pop.mail.yahoo.com.cn(端口:995) SMTP服務(wù)器地址:smtp.mail.yahoo.com.cn(端口:587

HotMail
POP3服務(wù)器地址:pop3.live.com (端口:995) SMTP服務(wù)器地址:smtp.live.com (端口:587)
gmail(google.com)
POP3服務(wù)器地址:pop.gmail.com(SSL啟用 端口:995) SMTP服務(wù)器地址:smtp.gmail.com(SSL啟用 端口:587)
263.net:
POP3服務(wù)器地址:pop3.263.net(端口:110) SMTP服務(wù)器地址:smtp.263.net(端口:25)
263.net.cn:
POP3服務(wù)器地址:pop.263.net.cn(端口:110) SMTP服務(wù)器地址:smtp.263.net.cn(端口:25)
x263.net:
POP3服務(wù)器地址:pop.x263.net(端口:110) SMTP服務(wù)器地址:smtp.x263.net(端口:25)
21cn.com:
POP3服務(wù)器地址:pop.21cn.com(端口:110) SMTP服務(wù)器地址:smtp.21cn.com(端口:25)
Foxmail:
POP3服務(wù)器地址:POP.foxmail.com(端口:110) SMTP服務(wù)器地址:SMTP.foxmail.com(端口:25)
china.com:
POP3服務(wù)器地址:pop.china.com(端口:110) SMTP服務(wù)器地址:smtp.china.com(端口:25)
tom.com:
POP3服務(wù)器地址:pop.tom.com(端口:110) SMTP服務(wù)器地址:smtp.tom.com(端口:25)
etang.com:
POP3服務(wù)器地址:pop.etang.com SMTP服務(wù)器地址:smtp.etang.com

關(guān)于“如何使用java來發(fā)送郵件”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“如何使用java來發(fā)送郵件”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

分享標(biāo)題:如何使用java來發(fā)送郵件
轉(zhuǎn)載源于:http://bm7419.com/article18/jddpdp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站制作、網(wǎng)站建設(shè)微信小程序、微信公眾號(hào)定制網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營