Java实现邮件收发

一,准备工作

1,传输协议

SMTP协议-->发送邮件:
我们通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)

POP3协议-->接收邮件:
我们通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)

2,邮件收发原理

在这里插入图片描述

  1. 闪电侠网易云邮箱通过smtp协议连接到Smtp服务器,然后发送一封邮件给网易的邮件服务器
  2. 网易分析发现需要去QQ的邮件服务器,通过smtp协议将邮件转投给QQ的Smtp服务器
  3. QQ将接收到的邮件存储在 [email protected]这个邮件账号的空间中
  4. 闪电侠qq邮箱通过Pop3协议连接到Pop3服务器收取邮件
  5. [email protected]这个邮件账号的空间中取出邮件
  6. Pop3服务器将取出来的邮件送到闪电侠qq邮箱中

3,QQ邮箱中获取对应的权限

QQ邮箱需要安全验证,我们需要获取他对应的权限;
QQ邮箱-->邮箱设置-->账户
在这里插入图片描述
在这里插入图片描述

4,导入jar包

mail.jar
activation.ja

二,Java发送纯文本邮件

1, 编写测试代码

public class SendMain {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {

        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host", "smtp.qq.com");
        //邮件发送协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //需要验证用户名密码
        prop.setProperty("mail.smtp.auth", "true");

        //关于QQ邮箱,还要设置SSL加密,加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //使用JavaMail发送邮件的5个步骤
        //1.txt、创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("[email protected]",
                        "授权码");
            }
        });

        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        //2、通过session得到transport对象
        Transport ts = session.getTransport();

        //3、使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "[email protected]", "授权码");

        //4,创建邮件
        //4-1.txt,创建邮件对象
        MimeMessage message = new MimeMessage(session);

        //4-2,指明邮件的发件人
        message.setFrom(new InternetAddress("[email protected]"));

        //4-3,指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

        //4-4,邮件标题
        message.setSubject("Hello");

        //4-5,邮件文本内容
        message.setContent("我是钢铁侠!", "text/html;charset=UTF-8");

        //4-6,发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        //5,关闭连接
        ts.close();
    }
}

三,Java发送创建包含内嵌图片的邮件

1,导入图片

在这里插入图片描述

2,编写测试代码

public class SendMainpicture1 {
    public static void main(String[] args)throws GeneralSecurityException, MessagingException{
        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host", "smtp.qq.com");
        //邮件发送协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //需要验证用户名密码
        prop.setProperty("mail.smtp.auth", "true");

        //关于QQ邮箱,还要设置SSL加密,加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //使用JavaMail发送邮件的5个步骤
        //1.txt、创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("[email protected]",
                        "授权码");
            }
        });
        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com", "[email protected]", "授权码");
        //4,创建邮件
        //4-1.txt,创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //4-2,指明邮件的发件人
        message.setFrom(new InternetAddress("[email protected]"));
        //4-3,指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        //4-4,邮件标题
        message.setSubject("Hello,钢铁侠");
        //5.准备图片
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src/resources/9.jpg"));
        image.setDataHandler(dh);
        image.setContentID("9.jpg");
        //6.准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:9.jpg'>的邮件", "text/html;charset=UTF-8");
        //7.描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");
        //设置到消息中,保存修改
        message.setContent(mm);
        message.saveChanges();
        //发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }
}

四,Java发送带图片和附件的复杂邮件

1,导入附件和图片

在这里插入图片描述

2,编写测试代码

public class SendMainpicture2 {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties prop = new Properties();
        //设置QQ邮件服务器
        prop.setProperty("mail.host", "smtp.qq.com");
        //邮件发送协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //需要验证用户名密码
        prop.setProperty("mail.smtp.auth", "true");

        //关于QQ邮箱,还要设置SSL加密,加上以下代码即可
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        //使用JavaMail发送邮件的5个步骤
        //1.txt、创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("[email protected]",
                        "授权码");
            }
        });
        //可以通过session开启Dubug模式,查看所有的过程
        session.setDebug(true);


        //2.获取连接对象,通过session对象获得Transport,需要捕获或者抛出异常;
        Transport tp = session.getTransport();
        //3.连接服务器,需要抛出异常;
        tp.connect("smtp.qq.com","[email protected]","授权码");
        //4.连接上之后我们需要发送邮件;
        MimeMessage mimeMessage = imageMail(session);
        //5.发送邮件
        tp.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //6.关闭连接
        tp.close();
    }

    public static MimeMessage imageMail(Session session) throws MessagingException {
        //消息的固定信息
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("[email protected]"));
        //邮件接收人,可以同时发送给很多人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        mimeMessage.setSubject("我也不知道是个什么东西就发给你了"); //邮件主题

        //图片
        MimeBodyPart body1 = new MimeBodyPart();
        body1.setDataHandler(new DataHandler(new FileDataSource("src/resources/9.jpg")));
        body1.setContentID("9.jpg"); //图片设置ID

        //文本
        MimeBodyPart body2 = new MimeBodyPart();
        body2.setContent("请注意,我不是广告<img src='cid:9.jpg'>","text/html;charset=utf-8");

        //附件
        MimeBodyPart body3 = new MimeBodyPart();
        body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/log4j.properties")));
        body3.setFileName("log4j.properties"); //附件设置名字

        MimeBodyPart body4 = new MimeBodyPart();
        body4.setDataHandler(new DataHandler(new FileDataSource("src/resources/1.txt")));
        body4.setFileName("1.txt"); //附件设置名字

        //拼装邮件正文内容
        MimeMultipart multipart1 = new MimeMultipart();
        multipart1.addBodyPart(body1);
        multipart1.addBodyPart(body2);
        multipart1.setSubType("related"); //1.txt.文本和图片内嵌成功!

        //new MimeBodyPart().setContent(multipart1); //将拼装好的正文内容设置为主体
        MimeBodyPart contentText =  new MimeBodyPart();
        contentText.setContent(multipart1);

        //拼接附件
        MimeMultipart allFile =new MimeMultipart();
        allFile.addBodyPart(body3); //附件
        allFile.addBodyPart(body4); //附件
        allFile.addBodyPart(contentText);//正文
        allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed;

        //放到Message消息中
        mimeMessage.setContent(allFile);
        mimeMessage.saveChanges();//保存修改

        return mimeMessage;
    }
}

猜你喜欢

转载自www.cnblogs.com/tqsh/p/11313896.html