基于javax.mail简单邮件发送

准备工作

1、Java架包(javax.mail-1.5.0.jar)
2、搭建Java工程

Java工程

3、对应图片创建文件目录
com.ding.test---测试类
com.ding.tools---邮件类
mail.properties---邮件配置类

开始代码

1、先看看要写哪些类

邮件发送类

2、代码走起
Constants.java

package com.ding.tools;

import java.io.IOException;
import java.util.Properties;

public class Constants {
    private static String filename = "mail.properties";
    public static String mailHost = "";
    public static String mailPort = "";
    public static String userName = "";
    public static String mailPwd = "";
    public static String fromAddr = "";
    public static String mailurl = "";

    static {
        Properties prop = new Properties();
        try {
            prop.load(Constants.class.getClassLoader().getResourceAsStream(filename));
            mailHost = prop.getProperty("mail.mailHost").trim();
            mailPort = prop.getProperty("mail.mailPort").trim();
            userName = prop.getProperty("mail.userName").trim();
            mailPwd = prop.getProperty("mail.pwd").trim();
            fromAddr = prop.getProperty("mail.fromAddr").trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MailAuthenticator.java

package com.ding.tools;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {
    String userName = null;
    String password = null;

    public MailAuthenticator() {
    }

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

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(this.userName, this.password);
    }
}

MailSend.java

package com.ding.tools;

import java.util.List;

public class MailSend {
    public static boolean ExecuteMailSends(String mailSubject, String mailContent, List<String> emails) {
        boolean flag = false;
        String mailHost = Constants.mailHost;
        String mailPort = Constants.mailPort;
        String userName = Constants.userName;
        String pwd = Constants.mailPwd;
        String fromAddr = Constants.fromAddr;
        if ((mailHost == null) || ("".equals(mailHost)) || (mailPort == null) || ("".equals(mailPort))
                || (userName == null) || ("".equals(userName)) || (pwd == null) || ("".equals(pwd))
                || (fromAddr == null) || ("".equals(fromAddr))) {
            return flag;
        }
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost(mailHost);
        mailInfo.setMailServerPort(mailPort);
        mailInfo.setValidate(true);
        mailInfo.setUserName(userName);
        mailInfo.setPassword(pwd);
        mailInfo.setFromAddress(fromAddr);
        mailInfo.setSubject(mailSubject);
        mailInfo.setContent(mailContent);

        flag = SimpleMailSenderImpl.sendHtmlMails(mailInfo, emails);
        return flag;
    }

    public static boolean ExecuteMailSend(String mailSubject, String mailContent, String email) {
        boolean flag = false;
        String mailHost = Constants.mailHost;
        String mailPort = Constants.mailPort;
        String userName = Constants.userName;
        String pwd = Constants.mailPwd;
        String fromAddr = Constants.fromAddr;
        if ((mailHost == null) || ("".equals(mailHost)) || (mailPort == null) || ("".equals(mailPort))
                || (userName == null) || ("".equals(userName)) || (pwd == null) || ("".equals(pwd))
                || (fromAddr == null) || ("".equals(fromAddr))) {
            return flag;
        }
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setMailServerHost(mailHost);
        mailInfo.setMailServerPort(mailPort);
        mailInfo.setValidate(true);
        mailInfo.setUserName(userName);
        mailInfo.setPassword(pwd);
        mailInfo.setFromAddress(fromAddr);

        mailInfo.setSubject(mailSubject);
        mailInfo.setContent(mailContent);
        mailInfo.setToAddress(email);

        flag = SimpleMailSenderImpl.sendHtmlMail(mailInfo);

        return flag;
    }

    private static String lpad(int length, int number) {
        String f = "%0" + length + "d";
        return String.format(f, new Object[] { Integer.valueOf(number) });
    }
}

MailSenderInfo.java

package com.ding.tools;

import java.util.Properties;

public class MailSenderInfo {
    private String mailServerHost;
    private String mailServerPort;
    private String fromAddress;
    private String toAddress;
    private String userName;
    private String password;
    private boolean validate = false;
    private String subject;
    private String content;
    private String[] attachFileNames;

    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", this.validate ? "true" : "false");
        return p;
    }

    public String getMailServerHost() {
        return this.mailServerHost;
    }

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

    public String getMailServerPort() {
        return this.mailServerPort;
    }

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

    public boolean isValidate() {
        return this.validate;
    }

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

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

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

    public String getFromAddress() {
        return this.fromAddress;
    }

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

    public String getPassword() {
        return this.password;
    }

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

    public String getToAddress() {
        return this.toAddress;
    }

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

    public String getUserName() {
        return this.userName;
    }

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

    public String getSubject() {
        return this.subject;
    }

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

    public String getContent() {
        return this.content;
    }

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

SimpleMailSenderImpl.java

package com.ding.tools;

import java.util.Date;
import java.util.List;
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;

public class SimpleMailSenderImpl {
    public boolean sendTextMail(MailSenderInfo mailInfo) {
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);

            Address from = new InternetAddress(mailInfo.getFromAddress());

            mailMessage.setFrom(from);

            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);

            mailMessage.setSubject(mailInfo.getSubject());

            mailMessage.setSentDate(new Date());

            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);

            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
        boolean flag = false;
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);

            Address from = new InternetAddress(mailInfo.getFromAddress());

            mailMessage.setFrom(from);

            Address to = new InternetAddress(mailInfo.getToAddress());

            mailMessage.setRecipient(Message.RecipientType.TO, to);

            mailMessage.setSubject(mailInfo.getSubject());

            mailMessage.setSentDate(new Date());

            Multipart mainPart = new MimeMultipart();

            BodyPart html = new MimeBodyPart();

            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);

            mailMessage.setContent(mainPart);

            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            flag = false;
            ex.getMessage();
            ex.printStackTrace();
        }
        return flag;
    }

    public static boolean sendHtmlMails(MailSenderInfo mailInfo, List<String> recipients) {
        boolean flag = false;
        MailAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);

            Address from = new InternetAddress(mailInfo.getFromAddress());

            mailMessage.setFrom(from);

            int num = recipients.size();
            Address[] addss = new InternetAddress[num];
            for (int i = 0; i < num; i++) {
                addss[i] = new InternetAddress((String) recipients.get(i));
            }
            mailMessage.setRecipients(Message.RecipientType.TO, addss);

            mailMessage.setSubject(mailInfo.getSubject());

            mailMessage.setSentDate(new Date());

            Multipart mainPart = new MimeMultipart();

            BodyPart html = new MimeBodyPart();

            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);

            mailMessage.setContent(mainPart);

            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            flag = false;
            ex.getMessage();
            ex.printStackTrace();
        }
        return flag;
    }
}

mail.properties邮件配置

##邮件发送服务器
mail.mailHost=smtp.sina.com
##邮件发送服务器端口号
mail.mailPort=25
##邮件用户名
mail.userName=newsisyphus
##密码
mail.pwd=youjianmima
##邮件的地址(用于发送邮件)
mail.fromAddr=newsisyphus@sina.com

注意:##

1、有些代理发送的,要到邮箱中设置开启代理发件服务
2、对应的端口号,地址,用户名,请参考网上配置

Test.java

package com.ding.test;

import java.util.ArrayList;
import java.util.List;

import com.ding.tools.MailSend;

public class Test {

    public static void main(String[] args) {
        String email = "shoujianren@sss.com";//收件邮箱
        List<String> emails = new ArrayList();
        emails.add(email);
        MailSend tMail = new MailSend();
        String mailinfo = "<h1>test</h1>test<p>test</p><a href=\"#\">test</a>";//邮件内容
                String mailItem = "邮件主题";//邮件主题
        boolean sendflag = tMail.ExecuteMailSends(mailItem , mailinfo, emails);//发送邮件
        if (sendflag) {//判断是否成功
            System.out.println("success!!");
        }
    }
}

tMail.ExecuteMailSends(mailItem , mailinfo, emails);可以配置多个邮件
tMail.ExecuteMailSend方法发送单个邮件

对于邮件发送还有什么问题,可以联系我qq:461874689

转载请注明出处,谢谢大家!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,324评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,356评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,328评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,147评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,160评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,115评论 1 296
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,025评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,867评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,307评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,528评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,688评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,409评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,001评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,657评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,811评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,685评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,573评论 2 353

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,651评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,803评论 6 342
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,239评论 11 349
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,622评论 18 399
  • 当我们的角色发生了改变时,总是会有一些新的感悟。初为人母的我,在自己的视野所及之处,解读关于育儿的奥秘。 新生命的...
    1f2399d98068阅读 306评论 0 0