java mail 发送带有附件的邮件

本文详细介绍使用Java发送带有HTML内容及附件的邮件的过程,包括SMTP服务器配置、邮件内容设置、附件添加及发送操作,适用于Java邮件应用开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//创建属性对象(key-value)
        Properties pro = new Properties(); 
        pro.put("mail.smtp.auth", "true"); //发送服务器需要身份认证
        pro.put("mail.host", "smtp.qq.com");//设置邮件服务器
        pro.put("mail.transport.protocol", "smtp");//发送邮件的协议
        pro.put("mail.smtp.port", "465");//端口号
        //qq邮箱需要ssl加密
        pro.put("mail.smtp.socketFactory.port","465");
        pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        
        //创建会话对象
        Session session = Session.getInstance(pro);
        //创建消息对象
        Message message = new MimeMessage(session);
        //设置邮件的标题
        message.setSubject("测试邮件标题2"); 
        
        
        
        
        
        
        //内容附件对象
        Multipart part = new MimeMultipart();
        
        //文本内容
        BodyPart txt = new MimeBodyPart();
        //设置内容,格式
        txt.setContent("测试邮件内容2 <a href='https://www.baidu.com/'>百度一下</a>", "text/html;charset=utf-8");
        //把文本内容添加到part中
        part.addBodyPart(txt);
        
        //附件
        BodyPart addpendix = new MimeBodyPart();
        //数据源
        DataSource ds = new FileDataSource("F:\\yujun\\jar\\mail-1.4.7.jar");
        //添加附件
        addpendix.setDataHandler(new DataHandler(ds));
        //设置附件的名称
        //addpendix.setFileName("mail-1.4.7.jar");
        addpendix.setFileName(MimeUtility.encodeText("邮件mail-1.4.7.jar")); //解决乱码
        //把附件添加到part中
        part.addBodyPart(addpendix);
        
        //把part添加到消息对象中
        message.setContent(part);
        
        
        
        //设置发送人
        message.setFrom(new InternetAddress("2960036795@qq.com"));
        //设置接收人
        message.setRecipient(RecipientType.TO, new InternetAddress("1156380111@qq.com"));
        //创建消息发送对象
        Transport tran = session.getTransport();
        //链接         发送人       授权码
        tran.connect("2960036795@qq.com","ushychpeqzkmdcdj");
        //发送消息
        tran.sendMessage(message, message.getAllRecipients());
        //关闭
        tran.close();
        System.out.println("邮箱发送完毕....");

 

转载于:https://www.cnblogs.com/chyxOne/p/9686075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值