栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaWeb邮件发送

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaWeb邮件发送

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

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

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

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

  • jar


		javax.mail
		mail
		1.4.7




		javax.activation
		activation
		1.1.1

  • 简单邮件
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("这是一封正文带有图片的邮件", "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("邮件标题");
        //准备邮件数据
        
        //准备图片数据
        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("这不是广告", "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();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880051.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号