前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java之jmail实现邮件发送

java之jmail实现邮件发送

作者头像
周杰伦本人
发布2023-10-12 13:57:45
2260
发布2023-10-12 13:57:45
举报
文章被收录于专栏:同步文章

闲着没事写个用jmail发送邮件的功能

1.所需jar包
代码语言:javascript
复制
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.1</version>
</dependency>

还要注意的是 邮箱要smtp服务

这里写图片描述
这里写图片描述
2.直接贴代码吧。。
代码语言:javascript
复制
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.FileInputStream;
import java.util.Properties;

public class Mail {

    private MimeMessage mimeMessage;//Mime邮件对象
    private Session session;//邮件会话对象
    private Properties properties;//系统属性
    private boolean needAuth = false;//smtp是否需要认证
    //smtp认证的用户名和密码
    private String username;
    private String password;
    private Multipart multipart;//Multipart对象 邮件内容 标题 附件等内容添加到这里面 然后生成MimeMessage对象

    /**
     * 构造方法
     * @param smtp
     */
    public Mail(String smtp){
        setSmtpHost(smtp);
        createMimeMessage();
    }

    /**
     * 创建MimeMessage邮件对象
     * @return
     */
    public boolean createMimeMessage() {
        //获取邮件会话对象
        session = Session.getDefaultInstance(properties, null);
        //创建Mime邮件对象
        mimeMessage = new MimeMessage(session);
        multipart = new MimeMultipart();
        return true;
    }

    /**
     *  设置邮件发送服务器
     * @param hostName
     */
    public void setSmtpHost(String hostName) {
        if (properties==null){
            properties=System.getProperties();//获得系统属性对象
        }
        properties.put("mail.smtp.host",hostName);//设置smtp主机
    }

    /**
     * 设置smtp是否需要认证
     * @param need
     */
    public void setNeedAuth(boolean need){
        if (properties == null){
            properties = System.getProperties();
        }
        if (need){
            properties.put("mail.smtp.auth","true");
        }else {
            properties.put("mail.smtp.auth","false");
        }
    }

    /**
     * 发件人的用户名和密码 163的用户名就是邮箱的前缀
     * @param username
     * @param password
     */
    public void setNamePassword(String username,String password){
        this.username = username;
        this.password = password;
    }

    /**
     * 邮件主题
     * @param subject
     * @return
     */
    public boolean setSubject(String subject){
        try {
            mimeMessage.setSubject(subject);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 邮件正文
     * @param mailBody
     * @return
     */
    public boolean setBody(String mailBody){
        BodyPart bodyPart = new MimeBodyPart();
        try {
            bodyPart.setContent(""+mailBody,"text/html;charset=utf-8");
            multipart.addBodyPart(bodyPart);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 邮件正文(带图片的)
     * @param mailBody
     * @param imgFile
     * @return
     */
    public boolean setBodyWithImg(String mailBody,String imgFile){
        BodyPart content = new MimeBodyPart();
        BodyPart img = new MimeBodyPart();
        try {
            multipart.addBodyPart(content);
            multipart.addBodyPart(img);

            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(new FileInputStream(imgFile),"application/octet-stream");
//            DataHandler imgDataHandler = new DataHandler(new FileDataSource(imgFile));
            DataHandler imgDataHandler = new DataHandler(byteArrayDataSource);
            img.setDataHandler(imgDataHandler);
//            img.setContent
            String imgFilename = imgFile.substring(imgFile.lastIndexOf("/")+1);//图片文件名
            //注意:Content-ID的属性值一定要加上<>,不能直接写文件名
            String headerValue = "<"+imgFilename+">";
            img.setHeader("Content-ID",headerValue);
            //为图片设置文件名,有的邮箱会把html内嵌的图片也当成附件
            img.setFileName(imgFilename);
            //在html代码中要想显示刚才的图片名 src里不能直接写Content-ID的值,要用cid:这种方式
            mailBody+="<img src='cid:"+imgFilename+"' alt='picture' width='100px' height='100px' />,骚吗?";
            content.setContent(""+mailBody,"text/html;charset=utf-8");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 邮件添加附件
     * @param file
     * @return
     */
    public boolean addFileAffix(String file){
        String[] fileArray = file.split(",");

        for (int i = 0; i < fileArray.length; i++) {
            FileDataSource fileDataSource = new FileDataSource(fileArray[i]);
            try {
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setDataHandler(new DataHandler(fileDataSource));
                bodyPart.setFileName(fileDataSource.getName());
                multipart.addBodyPart(bodyPart);
            } catch (MessagingException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 发件人邮箱
     * @param from
     * @return
     */
    public boolean setFrom(String from){
        try {
            mimeMessage.setFrom(new InternetAddress(from));
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 收件人邮箱
     * @param to
     * @return
     */
    public boolean setTo(String to){
        if (to==null)
            return false;
        try {
            //电子邮件可以有三种类型的收件人,分别to、cc(carbon copy)和bcc(blind carbon copy),分别是收件人、抄送、密送
            mimeMessage.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 抄送人邮箱 字符串中逗号分开
     * @param copyto
     * @return
     */
    public boolean setCopyTo(String copyto){
        if (copyto == null)
            return false;
        try {
            mimeMessage.setRecipients(Message.RecipientType.CC,(Address[]) InternetAddress.parse(copyto));
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送
     * @param copyto
     * @return
     */
    public boolean sendOut(String copyto){
        try {
            //multipart放入message
            mimeMessage.setContent(multipart);
            mimeMessage.saveChanges();
            Session mailSession = Session.getInstance(properties, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect(properties.getProperty("mail.smtp.host"),username,password);
            transport.sendMessage(mimeMessage,mimeMessage.getRecipients(Message.RecipientType.TO));
            if (copyto!=null){
                transport.sendMessage(mimeMessage,mimeMessage.getRecipients(Message.RecipientType.CC));
            }
            System.out.println("邮件发送成功");
            transport.close();
            return true;
        } catch (MessagingException e) {
            System.out.println("邮件发送失败");
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 该方法调用上边定义的方法 选择性的组合 完成邮件发送
     * 普普通通的一对一发送
     * @param smtp
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param username
     * @param password
     * @return
     */
    public static boolean send(String smtp,String from,String to,String subject,
                               String content,String username,String password){
        Mail mail = new Mail(smtp);
        mail.setNeedAuth(true);//需要认证
        if (!mail.setSubject(subject))
            return false;
        if (!mail.setBody(content))
            return false;
        if (!mail.setFrom(from))
            return false;
        if (!mail.setTo(to)){
            return false;
        }
        mail.setNamePassword(username,password);
        if (!mail.sendOut(null))
            return false;
        return true;
    }

    /**
     * 带附件的正文有图片的带有抄送的邮件
     * @return
     */
    public static boolean sendAndCcWithFile(String smtp,String from,String to,String subject,
                                            String content,String imageFile,String username,String password,String copyto,String filename){
        Mail mail = new Mail(smtp);
        mail.setNeedAuth(true);//需要认证
        if (!mail.setSubject(subject)) {
            return false;
        }
        if (!mail.setBodyWithImg(content,imageFile)) {
            return false;
        }
        if (!mail.addFileAffix(filename))
            return false;
        if (!mail.setFrom(from)) {
            return false;
        }
        if (!mail.setTo(to)){
            return false;
        }
        if (!mail.setCopyTo(copyto)) {
            return false;
        }
        mail.setNamePassword(username,password);
        if (!mail.sendOut(copyto))
            return false;
        return true;
    }
}

测试类:

代码语言:javascript
复制
package com.yannana.jmail;

import javax.mail.internet.MimeBodyPart;

public class MailTest {
    public static void main(String[] args) {
        String smtp ="smtp.163.com";//SMTP服务器地址
        String from = "xiepanpan1995@163.com";
        String to = "2908136316@qq.com";
        String copyto="xiepanpan2017@163.com,3068611755@qq.com";
        String subject = " 狗年大吉";
//        String content ="<h1>狗年大吉吧</h1>";
        MimeBodyPart img = new MimeBodyPart();

        String content ="<div style='color:red;font-size:18px;'>从163发来的邮件</div>我这里有一张自拍";
        //正文中的图片
        String imgFile="D:/binaryzation/wuyanzu.jpg";
        //附件
        String filename = "D:/binaryzation/binaryzation-wuyanzu.jpg,D:/binaryzation/newPic.jpg";
        //163邮箱用户名就是去掉@163.com
        String username = "你的用户名";
        String password = "你的邮箱密码";

//        Mail.send(smtp,from,to,subject,content,username,password);
        Mail.sendAndCcWithFile(smtp,from,to,subject,content,imgFile,username,password,copyto,filename);
    }
}

完事效果如下:

这里写图片描述
这里写图片描述

参考文章:

https://zhidao.baidu.com/question/1431992442917304139.html

http://blog.csdn.net/zyh5540/article/details/19018363

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-10-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.所需jar包
  • 2.直接贴代码吧。。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档