JavaWeb邮件发送

JavaMail是sur公司为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包。它支持一些常用的邮件协议,如SMTP,POP3,IMAP,还有MIME等。我们在使用JavaMail API编写邮件时,无须考虑邮件的底层实现细节,只要调用JavaMail开发包中相应的API类就可以了。

我们可以先尝试发送一封简单的邮件,确保电脑可以连接网络:

  • 创建包含邮件服务器的网络连接信息的session对象;
  • 创建代表邮件内容的Message对象;
  • 创建Transport对象,连接服务器,发送Message,关闭连接。

主要有四个核心类,我们在编写程序时,记住这四个核心类,就很容易编写出Java邮件处理程序:
在这里插入图片描述

  • jar
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
		<groupId>javax.mail</groupId>
		<artifactId>mail</artifactId>
		<version>1.4.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
		<groupId>javax.activation</groupId>
		<artifactId>activation</artifactId>
		<version>1.1.1</version>
</dependency>
  • 简单邮件
package com.wang;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

//发送一封简单的邮件
public class MailDemo01 {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//设置QQ邮箱服务器
        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.创建自定义整个应用程序所需要的环境信息的Session对象(其他邮箱不用)
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            //发件人邮箱用户名、授权码
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });
        //开启Session的Debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连接上邮件服务器
        ts.connect("smtp.qq.com", "", "");
        //4.创建邮件
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发送人
        message.setFrom(new InternetAddress(""));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));
        //邮件的标题
        message.setSubject("只包含文本的简单邮件");
        //邮件的文本内容
        message.setContent("你好", "text/html;charset=UTF-8");
        //5.发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        //6.关闭
        ts.close();
    }
}
  • 添加图片邮件类型
  • MIME(多用途互联网邮件扩展类型)
    • MimeBodyPart类
      • javax.mail.internet.MimeBodyPart类表示的是一个MIME消息,它和MimeMessage类一样都是从Part接口继承过来。
    • MimeMultipart类
      • javax.mail.internet.MimeMultipart是抽象类Multipart的实现子类,它用来组合多个MIME消息。一个MimeMultipart对象可以包含多个代表MIME消息的MimeBodyPart对象。
package com.wang;

import com.sun.mail.util.MailSSLSocketFactory;


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 java.security.GeneralSecurityException;
import java.util.Properties;

public class MailDemo02 {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//设置QQ邮箱服务器
        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.创建自定义整个应用程序所需要的环境信息的Session对象(其他邮箱不用)
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            //发件人邮箱用户名、授权码
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });
        //开启Session的Debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连接上邮件服务器
        ts.connect("smtp.qq.com", "", "");
        //4.创建邮件
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //设置邮件的基本信息
        //指明邮件的发送人
        message.setFrom(new InternetAddress(""));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));
        //邮件的标题
        message.setSubject("带图片的邮件");
        //准备邮件数据
        //准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src/resources/picture.jpg"));
        image.setDataHandler(dh);
        image.setContentID("picture.jpg");//给图片设置一个ID
        //准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封正文带有图片的邮件<img src = 'cid:picture.jpg'>", "text/thml;charset=utf-8");
        //描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");//(内嵌related;mixed附件)
        //设置到消息中,保存修改
        message.setContent(mm);
        message.saveChanges();
        //5.发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        //6.关闭
        ts.close();
    }
}
  • 添加附件类型邮件
	package com.wang;

import com.sun.mail.util.MailSSLSocketFactory;

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 java.security.GeneralSecurityException;
import java.util.Properties;

public class MailDemo03 {
    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");//设置QQ邮箱服务器
        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.创建自定义整个应用程序所需要的环境信息的Session对象(其他邮箱不用)
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            //发件人邮箱用户名、授权码
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });
        //开启Session的Debug模式,这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();
        //3.使用邮箱的用户名和授权码连接上邮件服务器
        ts.connect("smtp.qq.com", "", "");


        //4.创建邮件
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //设置邮件的基本信息
        //指明邮件的发送人
        message.setFrom(new InternetAddress(""));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(""));
        //邮件的标题
        message.setSubject("邮件标题");
        //准备邮件数据
        /*
        编写邮件内容
        1.图片
        2.附件
        3.文本
        */
        //准备图片数据
        MimeBodyPart body1 = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src/resources/picture.jpg"));
        body1.setDataHandler(dh);
        body1.setContentID("picture.jpg");//给图片设置一个ID
        //文本
        MimeBodyPart body2 = new MimeBodyPart();
        body2.setContent("这不是广告<img src = 'cid:picture.jpg'>", "text/thml;charset=utf-8");

        //文本
        MimeBodyPart body3 = new MimeBodyPart();
        body3.setDataHandler(new DataHandler(new FileDataSource("src/resources/1.txt")));
        body3.setFileName("1.txt");

        //拼装邮件正文内容
        MimeMultipart mm1 = new MimeMultipart();
        mm1.addBodyPart(body1);
        mm1.addBodyPart(body2);
        mm1.setSubType("related");//1.文本和图片内嵌成功
        //将拼装好的正文内容设置为主体
        //new MimeBodyPart().setContent(mm1);
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mm1);

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

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

        //5.发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        //6.关闭
        ts.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值