java發(fā)送郵件(附件可選)

java實現(xiàn)發(fā)送郵件嘱丢,可以帶附件發(fā)送薪介。。屿讽。昭灵。。伐谈。

pom.xml:

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.1</version>
        </dependency>

java代碼:

package com.jd.blackdragon.storm.service.impl;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;

/**
 * Created by dell on 2018-04-15.
 */
public class SendEmail {
    //發(fā)件郵箱的地址
    private final static String MAIL_NAME = "username";
    private final static String MAIL_ADDR = "username@xxx.com";
    //發(fā)件郵箱的密碼
    private final static String MAILPWD = "password";
    //設(shè)置發(fā)送郵件的協(xié)議,下面是163郵箱的SMTP服務(wù)器
    private final static String SMTP_HOST = "smtp.163.local";

    //主程序測試
    public static void main(String[] args) {

        //郵件內(nèi)容
        String content = "明細數(shù)據(jù)詳見附件:";
        //郵件主題
        String topic = "數(shù)據(jù)";
        //接收郵箱地址
        String address = "123@xxx.com";
        //發(fā)送附件路徑
        String filename = "F:/home/test/data.txt";

        //帶附件發(fā)送
        boolean tag = sendMail(topic, content, address, filename);
        System.out.println("帶附件發(fā)送"+tag);

        //不帶附件發(fā)送
        boolean tag1 = sendMail(topic, content, address);
        System.out.println("不帶附件發(fā)送" + tag1);
    }

    /**
     * @author yanawang
     * @Title: sendMail
     * @Description: 發(fā)送郵件(可以進行帶附件發(fā)送, 參數(shù)最后為附件地址)
     * @date 2018-2-24 下午 02:28
     * 參數(shù)順序說明:String topic, String content, String address,String file(文件地址選填)
     * 參數(shù)至少為3個(標(biāo)題烂完、內(nèi)容、接收人地址)
     * 接收人地址可以設(shè)置多個诵棵,使用','進行分割抠蚣。如:123@163.com,456@163.com
     */
//    public static boolean sendMail(String topic, String content, String address) {
    public static boolean sendMail(String... strArray) {
        boolean bool = false;

        System.out.println(strArray.length);
        if (strArray.length < 3) {
            return bool;
        }
        try {
            String topic = strArray[0];
            String content = strArray[1];
            String address = strArray[2];
            Address[] addressTO = setAddressTo(address);
            MimeMessage message = setMessage(addressTO, topic);
            /*添加正文內(nèi)容*/
            Multipart multipart = new MimeMultipart();
            BodyPart contentPart = new MimeBodyPart();
//            contentPart.setText(content);
            contentPart.setContent(content, "text/html;charset=UTF-8");
            contentPart.setHeader("Content-Type", "text/html; charset=utf-8");
            multipart.addBodyPart(contentPart);

            /*添加附件*/
            if (strArray.length > 3) {
                String file = strArray[3];
                File usFile = new File(file);
                MimeBodyPart fileBody = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                fileBody.setDataHandler(new DataHandler(source));
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                fileBody.setFileName("=?GBK?B?"
                        + enc.encode(usFile.getName().getBytes()) + "?=");
                multipart.addBodyPart(fileBody);
            }
            message.setContent(multipart);
            message.setSentDate(new Date());
            message.saveChanges();
            Transport.send(message);
            bool = true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * @author yanawang
     * @Title: setMessage
     * @Description: 設(shè)置郵箱信息
     * @date 2018-2-5 上午 11:20
     */
    private static MimeMessage setMessage(Address[] addressTO, String topic)
            throws MessagingException {

        final Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.user", MAIL_NAME);
        props.put("mail.addr", MAIL_ADDR);
        props.put("mail.password", MAILPWD);
        Authenticator authenticator = new Authenticator() {
            protected 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);
        InternetAddress form = new InternetAddress(
                props.getProperty("mail.addr"));
        message.setFrom(form);
        message.setRecipients(Message.RecipientType.TO, addressTO);
        message.setSubject(topic);
        message.addHeader("charset", "UTF-8");
        return message;
    }

    /**
     * @author yanawang
     * @Title: setAddressTo
     * @Description: 設(shè)置郵箱地址
     * @date 2018-2-5 上午 11:20
     */
    private static Address[] setAddressTo(String address) throws AddressException {
        String[] tmpAddress = address.split(",");
        Address[] addressTO = new InternetAddress[tmpAddress.length];
        for (int i = 0; i < tmpAddress.length; i++) {
            addressTO[i] = new InternetAddress(tmpAddress[i]);
        }
        return addressTO;
    }


}



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市履澳,隨后出現(xiàn)的幾起案子嘶窄,更是在濱河造成了極大的恐慌,老刑警劉巖距贷,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柄冲,死亡現(xiàn)場離奇詭異,居然都是意外死亡忠蝗,警方通過查閱死者的電腦和手機现横,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來阁最,“玉大人戒祠,你說我怎么就攤上這事∷僦郑” “怎么了姜盈?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長配阵。 經(jīng)常有香客問我馏颂,道長示血,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任饱亮,我火速辦了婚禮矾芙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘近上。我一直安慰自己剔宪,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布壹无。 她就那樣靜靜地躺著葱绒,像睡著了一般。 火紅的嫁衣襯著肌膚如雪斗锭。 梳的紋絲不亂的頭發(fā)上地淀,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機與錄音岖是,去河邊找鬼帮毁。 笑死,一個胖子當(dāng)著我的面吹牛豺撑,可吹牛的內(nèi)容都是我干的烈疚。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼聪轿,長吁一口氣:“原來是場噩夢啊……” “哼爷肝!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起陆错,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤灯抛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后音瓷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體对嚼,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖似扔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情屯换,我是刑警寧澤驻仅,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站摆舟,受9級特大地震影響亥曹,放射性物質(zhì)發(fā)生泄漏邓了。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一媳瞪、第九天 我趴在偏房一處隱蔽的房頂上張望骗炉。 院中可真熱鬧,春花似錦蛇受、人聲如沸句葵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽乍丈。三九已至,卻和暖如春把将,著一層夾襖步出監(jiān)牢的瞬間轻专,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工察蹲, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留请垛,地道東北人。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓洽议,卻偏偏與公主長得像宗收,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子绞铃,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容