java写邮件发送,带图片


import com.sun.mail.util.MailSSLSocketFactory;

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



//发送照片的邮件协议
public class Test {
    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");//验证用户账号密码



        //要设置ssl加密,固定代码,针对大厂
        MailSSLSocketFactory sf=new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);
       

        //发送邮件,五个步骤

        //1.创建定义整个应用程序所需的环境信息的 session 对象

        //qq才有
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("@qq.com","授权码");
            }

        });
        //开启session的debug,查看邮件发送的运行状态
        session.setDebug(true);
        //2.通过session得到transport
        Transport ts=session.getTransport();
        //3.使用邮箱的用户名和授权码连接服务器 ?
        ts.connect("smtp.qq.com","@qq.com","授权码");
        //4.写邮件
        MimeMessage message=new MimeMessage(session);

        //指明发件人
        message.setFrom(new InternetAddress("@qq.com"));
        //收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("2481420844@qq.com"));
        //邮件标题
        message.setSubject("纯文本邮件");


        //邮件内容
        //准备图片数据
        MimeBodyPart image=new MimeBodyPart();
        DataHandler dh=new DataHandler(new FileDataSource("绝对路径/1.jpg"));
        image.setDataHandler(dh);
        //id自己设置
        image.setContentID("qx.jpg");
        //正文
        MimeBodyPart text=new MimeBodyPart();
        text.setContent("带图片的邮件<img src='cid:qx.jpg'>","text/html;charset=UTF-8");
       // message.setContent("<h1 style='color:red'>带图片的邮件<img src='cid:bz.jpg'></h1>","text/html;charset=UTF-8");

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

        //设置到消息中保存修改
        message.setContent(mm);
        message.saveChanges();
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();
    }
}

记得下载所需的包啊,可参考纯文本邮件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值