邮箱发送邮件(包含附件,网易、QQ)

效果图

在这里插入图片描述

代码

package com.mabo.email;

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.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 * @Author mabo
 * @Description   smtp服务
 * 发送邮件
 * 支持发送者的邮箱为:网易邮箱、QQ邮箱、139邮箱
 * 接收邮箱不限
 * 推荐使用QQ的smtp服务器,速度更快
 * 不推荐使用139邮箱
 * 139邮箱,无法发送不带附件的邮件
 */

public class EmailTest{
    //QQsmtp服务器
    private static final String QQHost="smtp.qq.com";
    private static final String QQPort="587";
    //网易smtp服务器
    private static final String WangYiHost="smtp.163.com";
    private static final String WangYiPort="25";
    //139邮箱,无法发送不带附件的
    private static final String E139Host="smtp.139.com";
    private static final String E139Port="25";

    public static void main(String[] args) throws Exception {
        //发送人邮箱是qq邮箱
        String username="xxx35619@qq.com";
        //配置QQsmtp服务器成功后的令牌
        String password="xxxsfqvondjee";
        //接受邮件的地址1
        String receive1="xxx22@163.com";
        //接受邮件的地址2
        String receive2="xxx2129@qq.com";

//        //发送人是网易邮箱
//        String username = "xxx0222@163.com";
//        //配置网易smtp服务器成功后的令牌
//        String password = "xxxHWSRPNFHI";
//       //  接受邮件的地址1
//        String receive1="xxx5619@qq.com";

//        //发送人是139邮箱
//        String username = "xxx704@139.com";
//        //配置网易smtp服务器成功后的令牌
//        String password = "xxx63ce95564ce00";
//        //接受邮件的地址1
//        String receive1="xxx9@qq.com";


        //发送的附件
        List<String> list=new ArrayList<>();
        list.add("F:/test.doc");
        list.add("F:/testw副本.doc");

        //邮件接收方集合
        List<String> listReceiver=new ArrayList<>();
        
        listReceiver.add(receive1);
        listReceiver.add(receive2);

        //发送不带附件的邮件
        sendEmailNoFile(username,password,receive1,"标题,无附件","正文,无附件");

        //发送带附件,多个接收者多附件的邮件
        sendEmail(username,password,listReceiver,"标题,带附件","正文,带附件",list);

        System.out.println("发送成功");
    }

    /**
     * @Author mabo
     * @Description   邮箱发送邮件,包含附件
     * String sender,发送者邮箱
     * String password ,邮箱令牌
     * List<String> receives,接受者邮箱集合
     * String subject,标题
     * String content,正文
     * List<String> files文件名称,为null不发送附件
     */
    public static void sendEmail(String sender,String password ,List<String> receivers,String subject, String content,List<String> files) throws Exception {
        String host;
        String port;
        if (sender.contains("@163.com")){
            host =WangYiHost;
            port =WangYiPort;
        }
        else if (sender.contains("@qq.com")){
            host =QQHost;
            port =QQPort;
        }
        else if (sender.contains("@139.com")){
            host =E139Host;
            port =E139Port;
        }
        else {
            throw  new Exception("当前发送者邮箱不支持smtp服务器");
        }
        // 创建Properties 类用于记录邮箱的一些属性
        Properties props = new Properties();
        // 表示SMTP发送邮件,必须进行身份验证
        props.put("mail.smtp.auth", "true");
        //此处填写SMTP服务器
        props.put("mail.smtp.host", host);
        //端口号,QQ邮箱端口587
        props.put("mail.smtp.port", port);
        // 此处填写,写信人的账号
        props.put("mail.user", sender);
        // 此处填写16位STMP口令
        props.put("mail.password", password);

        // 构建授权信息,用于进行SMTP进行身份验证
        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 session = Session.getInstance(props, authenticator);
        session.setDebug(true);
        try {
            List<File> attaches = new ArrayList<File>();
            if (files!=null){
                for (String file: files) {
                    File attach = new File(file);
                    attaches.add(attach);
                }
            }
            //根据session创建MimeMessage
            MimeMessage message = new MimeMessage(session);
            //发件人
            message.setFrom(new InternetAddress(sender));
            //收件人
            for (String receive:
                    receivers) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(receive));
            }


            //主题
            message.setSubject(subject);

            Multipart multipart = new MimeMultipart();
            //邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html;charset=utf-8");
            multipart.addBodyPart(contentPart);
            //邮件附件
            if(attaches.size()>0) {
                for(File attachment : attaches) {
                    BodyPart attachmentPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    attachmentPart.setDataHandler(new DataHandler(source));
                    //避免中文乱码的处理
                    attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                    multipart.addBodyPart(attachmentPart);
                }
            }
            message.setContent(multipart);
            //保存邮件
            message.saveChanges();
            Transport.send(message);
        } catch (AddressException e) {
            throw new AddressException("未找到接收邮箱");
        } catch (MessagingException e) {
            throw new MessagingException("发送失败");
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedEncodingException("发送失败");
        }


    }

    /**
     * @Author mabo
     * @Description   单对单发送邮件,不包含附件
     * String sender,发送者邮箱
     * String password ,邮箱令牌
     * String receives,接受者邮箱
     * String subject,标题
     * String content,正文
     */
    public static void sendEmailNoFile(String sender,String password ,String receiver,String subject, String content) throws Exception {
        ArrayList<String> objects = new ArrayList<>();
        objects.add(receiver);
        sendEmail(sender,password,objects,subject,content,null);
    }

}

如何开启QQ邮箱SMTP服务

网易和QQ邮箱的开启SMTP服务设置都差不多

  1. 进入邮箱,点击设置
    在这里插入图片描述
  2. 点击进入账户或者账户安全
    在这里插入图片描述
  3. 下滑找到SMTP服务,点击开启,安装提示步骤发送短信开启
    在这里插入图片描述
    在这里插入图片描述

4.短信验证成功,获取口令,即为代码中的password,然后就可以开始在代码中使用了
在这里插入图片描述

如何开启网易邮箱SMTP服务

  1. 进入首页,点击设置,点击POP3/SMTP/IMAP
    在这里插入图片描述

  2. 点击开启smtp服务
    在这里插入图片描述

  3. 根据提示,发送短信验证码,最终获取令牌,即可使用smtp服务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值