java发送纯正文及带附件的邮件

关于java发送邮件。我们可以利用com-mail-1.0.jar  包来实现。下面以QQ邮箱为列

//配置邮箱连接属性

        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号为数字
        properties.put("mail.smtp.auth", true);
        properties.put("mail.smtp.ssl.enable", true);// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", true);// 设置是否显示debug信息 true 会在控制台显示相关信息

        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(sendUserMail));
        // 设置收件人邮箱地址 
        message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(xxx@qq.com"),new InternetAddress(xxx@qq.com")});//多个
        //message.setRecipient(Message.RecipientType.TO, new InternetAddress("xxx@qq.com"));//一个收件人
        // 设置邮件标题
         message.setSubject("邮件标题");

     //1、邮件纯正正文。可以使用html的各种标签

     //  message.setContent("<p><b>正文:</b>我是内容</p>", "text/html;charset=UTF-8");
     

     //2、邮件需要附件
            File f = null;

            CommonsMultipartFile cf = (CommonsMultipartFile)file;  //此处file为前端提交后台控制层获取的文件MultipartFile file
            DiskFileItem fi = (DiskFileItem) cf.getFileItem(); 
            f = fi.getStoreLocation();
            Multipart multipart = new MimeMultipart();
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent("正文内容。可以使用html标签", "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);
            BodyPart messageBodyPart = new MimeBodyPart();
            
            DataSource source = new FileDataSource(f);
            // 添加附件的内容
            messageBodyPart.setDataHandler(new DataHandler(source));
            
            messageBodyPart.setFileName(MimeUtility.encodeText(file.getOriginalFilename(),"gb2312","B"));//避免附件标题乱码。个环境编码可能不同,自行测试
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

//带附件的结束

 message.saveChanges();
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(GlobalPropertiesHelper.getRequiredProperty("mail.smtp.host"),"xxx@qq.com", "授权码");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码,授权码在qq邮箱》设置》账户》POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务下开启“IMAP/SMTP服务“,点击生成授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        if(f != null){
            f.delete();//自己附件会保存在项目中。这里要删除,无附件邮件可以省略这一步
        }
        transport.close();
        
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值