邮件发送功能(Java语言实现)

 

引入依赖:

<dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>

首先在qq邮箱中开启邮件收发功能

发送简单邮件(纯文本)

package com.fdw.mail;

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 MailTest {
    //发送简单邮件
    public static void main(String[] args) throws Exception {
        //要发送协议,需要获得协议和支持,开启服务POP3/SMTP
        //授权码:oqudlrdmigwydigj
        final String passCode = "授权码";
        final String fromAddress = "发件邮箱";
         String toAddress = "收件邮箱";
         String subject = "天天开心";
        //邮件内容本质是html
         String content = "<h1 style='color: red'>你好啊</h1>";
        String type = "text/html;charset=utf-8";

        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.创建定义整个应用程序所需的环境信息的session对象
        //QQ才有
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication( ) {
                return new PasswordAuthentication(fromAddress,passCode);
            }
        });
        //session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com",fromAddress,passCode);
        //4.写邮件,注意需要传递session
        MimeMessage message = new MimeMessage(session);

        //发件人
        message.setFrom(new InternetAddress(fromAddress));
        //收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(toAddress));
        //邮件主题
        message.setSubject(subject);
        //正文
        message.setContent(content,type);
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        System.out.println("邮件发送成功");
        //6.关闭连接
        ts.close();

    }
}

 效果:

发送复杂邮件(带附件和图片)

 

代码

package com.fdw.mail;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

public class MailTest2 {
    //发送复杂邮件
    public static void main(String[] args) throws Exception {
        //要发送协议,需要获得协议和支持,开启服务POP3/SMTP
        //授权码:oqudlrdmigwydigj
        final String passCode = "oqudlrdmigwydigj";
        final String fromAddress = "2530155337@qq.com";
        String toAddress = "2043154068@qq.com";
        String subject = "天天开心";
        String content = "这是一封邮件带图片<img src='cid:bz.jpg'>的邮件";
        String type = "text/html;charset=utf-8";
        String imagePath = "E:\\IDEA项目\\JavaWebStudy\\Servlet-01\\src\\main\\resources\\1.png";
        String filePath = "E:\\IDEA项目\\JavaWebStudy\\Servlet-01\\src\\main\\resources\\请假申请表.docx";
        String imageID = "bz.jpg";
        String fileName = "请假申请表.docx";



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

        //关于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对象
        //QQ才有
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication( ) {
                return new PasswordAuthentication(fromAddress,passCode);
            }
        });
        //session.setDebug(true);
        //2.通过session得到transport对象
        Transport ts = session.getTransport();

        //3.使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com",fromAddress,passCode);
        //4.写邮件,注意需要传递session
        MimeMessage message = new MimeMessage(session);

        //发件人
        message.setFrom(new InternetAddress(fromAddress));
        //收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(toAddress));

        //邮件主题
        message.setSubject(subject);

        //文本
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content,type);

        //图片
        MimeBodyPart image = new MimeBodyPart();
        //图片需要经过数据处理
        FileDataSource imageDataSource = new FileDataSource(imagePath);
        DataHandler dh = new DataHandler(imageDataSource);
        image.setDataHandler(dh);
        //给图片设置一个ID,方便调用,cid:imageID
        image.setContentID(imageID);

        //附件
        MimeBodyPart file = new MimeBodyPart();
        FileDataSource fileDataSource = new FileDataSource(filePath);
        DataHandler dh2 = new DataHandler(fileDataSource);
        file.setDataHandler(dh2);
        //给附件设置文件名,并处理中文乱码
        file.setFileName(MimeUtility.encodeText(fileName));


        //描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");

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


        //拼接附件
        MimeMultipart allFile = new MimeMultipart();
        allFile.addBodyPart(file);
        allFile.addBodyPart(contentText);
        allFile.setSubType("mixed");


        //设置到消息中,保存修改
        message.setContent(allFile);
        message.saveChanges();
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        System.out.println("邮件发送成功");
        //6.关闭连接
        ts.close();

    }
}

效果

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThatMonth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值