Java implementation mail

First, the preparatory work

1, the transport protocol

SMTP protocol -> E-mail:
the server process we usually smtp user request (e-mail transmission request) is called SMTP server (mail server)

POP3 protocol -> receiving mail:
the server process we usually pop3 user request (e-mail reception request) called POP3 server (incoming mail server)

2, mail principle

Here Insert Picture Description

  1. Dwyane Netease cloud mail via smtp Smtp protocol to the server, and then send an e-mail to NetEase mail server
  2. Netease analysis found the need to QQ mail server via mail protocol smtp switch to QQ's Smtp server
  3. QQ received messages are stored in this space [email protected] mail account in
  4. Flash qq-mail server is connected to receive mail via Pop3 Pop3 protocol
  5. Remove the space [email protected] mail from the mail account in
  6. Pop3 server will be taken out of the mail sent to The Flash qq mailbox

3, QQ mailbox to obtain the corresponding permissions

QQ mailbox needed to verify safety, we need to get the permission of his correspondence;
QQ mailbox -> Mailbox Settings -> Accounts
Here Insert Picture Description
Here Insert Picture Description

4, introduced into the jar package

mail.jar
activation.ja

Two, Java send plain text messages

1, write test code

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();
    }
}

Three, Java sends a message that contains embedded images created

1, import pictures

Here Insert Picture Description

2, write test code

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();
    }
}

Four, Java complex mailing with pictures and attachments

1, import attachments and pictures

Here Insert Picture Description

2, write test code

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;
    }
}

Guess you like

Origin www.cnblogs.com/tqsh/p/11313896.html