java使用qq邮箱和exchange邮箱发送邮件,并携带附件

maven依赖

<!--  邮箱  -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.5.0-b01</version>
    </dependency>

qq邮箱工具类:

tip: 邮箱授权码,需要在qq邮箱里找到设置->常规->smtp服务,把POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务打开,获取到授权码。

package org.wq.email;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Email {

    public static final String SenderEmail = "123456@qq.com";//发送人邮箱
    public static final String senderCode = "";//发送人邮箱授权码
    public static final String emailSMTPHost = "smtp.qq.com";//服务器地址
    //public static final String receiveMailAccount = "123456@qq.com";//收件人邮箱

    /*发送邮件*/
    public static void sendMail(String path) {
        //收件人邮箱
        List<String> emailList = new ArrayList<>();
        emailList.add("123456@qq.com");
        //emailList.add("wangjj@numtop.com");

        for (String to : emailList) {
            try {
                Properties props = new Properties();
                props.setProperty("mail.transport.protocol", "smtp");// 使用的协议
                props.setProperty("mail.smtp.host", emailSMTPHost);// 发件人的邮箱的SMTP服务器地址
                props.setProperty("mail.smtp.auth", "true");// 需要请求认证

                Session session = Session.getInstance(props);//得到会话对象实例

                session.setDebug(false);//是否打印详细日志

                MimeMessage message = createMimeMessage(session,path,to);//获取邮件对象

                Transport transport = session.getTransport();

                transport.connect(SenderEmail, senderCode);//连接发送人的邮箱账户

                // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
                transport.sendMessage(message, message.getAllRecipients());

                // 7. 关闭连接
                transport.close();
                System.out.println("邮件发送成功!to=>" + to);
            } catch (Exception e) {
                System.out.println("邮件发送失败:"+ e);
            }
        }
    }


    public static MimeMessage createMimeMessage(Session session, String str, String to) throws Exception {
        //解析字符串,取出文件路径,文件名,content
        String[] split = str.split("@");

        String path = split[0];
        String fileName = split[1];
        String content = split[2];

        System.out.println("文件路径:"+path);
        System.out.println("文件名:"+fileName);
        System.out.println("content:"+content);

        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(SenderEmail, "发件人", "UTF-8"));

        // 3. 设置收件人、抄送人、密送人
        //MimeMessage.RecipientType.TO:收件类型;MimeMessage.RecipientType.CC:抄送类型;MimeMessage.RecipientType.BCC:密送类型
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to, "收件人", "UTF-8"));
//        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(ccMailAccount, "抄送人", "UTF-8"));
//        message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(bccmailAccount, "密送人", "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject("subject", "UTF-8");

        // 5. Content: 邮件正文(可以使用html标签)
        // 创建消息部分
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(content);

        // 创建多部分消息
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // 添加附件
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.attachFile(path); // 附件文件路径
        attachmentPart.setFileName(MimeUtility.encodeText(fileName+".xlsx")); // 对文件名进行编码
        multipart.addBodyPart(attachmentPart);

        // 设置消息内容
        message.setContent(multipart);


        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }
}

exchange邮箱工具类:

package org.wq.email;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class EmailByExChange {

    private static String from = "发送人邮箱";


    /**
     * 发送邮件
     * @param str
     */
    public static void sendMail(String str) throws GeneralSecurityException, MessagingException {
        //解析字符串,取出文件路径,文件名,content
        String[] split = str.split("@");

        String path = split[0];
        String fileName = split[1];
        String content = split[2];

        System.out.println("文件路径:"+path);
        System.out.println("文件名:"+fileName);
        System.out.println("content:"+content);

        //收件人邮箱
        List<String> emailList = new ArrayList<>();
        emailList.add("123456@qq.com");

        for (String to : emailList) {
            final String username = "admin";
            final String password = "admin";

            Properties props = new Properties();
            props.put("mail.smtp.host", "");//smtp地址
            props.put("mail.smtp.port", "");//端口
            props.put("mail.smtp.auth", "true");

            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });

            try {
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to));

                //主题
                message.setSubject("subject");

                // Create a multipart message
                Multipart multipart = new MimeMultipart();

                // 普通正文
                BodyPart messageBodyPart = new MimeBodyPart();
                List<String> list = Arrays.asList(content.split(","));
                String contentStr = "";
                for (String string : list) {
                    contentStr = contentStr + string + "\n";
                }
                System.out.println(contentStr);

                messageBodyPart.setText(contentStr);
                multipart.addBodyPart(messageBodyPart);

                //html正文(中文乱码)
//                List<String> list = Arrays.asList(content.split(","));
//                String contentStr = "";
//                for (String string : list) {
//                    contentStr = contentStr + string + "</br>";
//                }
//                System.out.println("html:"+contentStr);
//
//                BodyPart messageBodyPart = new MimeBodyPart();
//                String htmlContent = "<html><head><meta charset='UTF-8'/></head><body><p>"+
//                        contentStr
//                        +"</p></body></html>";
//                System.out.println(htmlContent);
//
//                messageBodyPart.setContent(htmlContent, "text/html");
//                multipart.addBodyPart(messageBodyPart);

                // 附件
                BodyPart attachmentPart = new MimeBodyPart();
                DataSource source = new FileDataSource(path);
                attachmentPart.setDataHandler(new DataHandler(source));

                // 文件名编码
                String encodedFileName = MimeUtility.encodeText(fileName + ".xlsx");
                attachmentPart.setFileName(encodedFileName);
                multipart.addBodyPart(attachmentPart);

                // Set the message content
                message.setContent(multipart);

                // Send the message
                Transport.send(message);

                System.out.println("邮件发送成功!to=>"+to);

            } catch (MessagingException e) {
                throw new RuntimeException(e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用JavaMailSender发送附件邮件qq邮箱的示例代码: ```java // 创建一个JavaMailSender实例 JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp.qq.com"); // 设置SMTP服务器地址 mailSender.setPort(587); // 设置SMTP服务器端口号 mailSender.setUsername("你的QQ邮箱账号"); // 设置发送邮件的账号 mailSender.setPassword("你的QQ邮箱授权码"); // 设置发送邮件的授权码 // 创建一个MimeMessage实例 MimeMessage message = mailSender.createMimeMessage(); // 使用MimeMessageHelper添加邮件内容和附件 MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom("你的QQ邮箱地址"); // 设置发件人邮箱 helper.setTo("收件人邮箱地址"); // 设置收件人邮箱 helper.setSubject("邮件主题"); // 设置邮件主题 helper.setText("邮件正文"); // 设置邮件正文 // 添加附件 FileSystemResource resource = new FileSystemResource(new File("附件路径")); helper.addAttachment("附件名称", resource); // 发送邮件 mailSender.send(message); ``` 其中,`setHost()`方法设置SMTP服务器地址,`setPort()`方法设置SMTP服务器端口号,`setUsername()`方法设置QQ邮箱账号,`setPassword()`方法设置QQ邮箱授权码。`MimeMessageHelper`类的`addAttachment()`方法用于添加附件,第一个参数为附件名称,第二个参数为附件文件资源。`FileSystemResource`类是Spring Framework提供的文件系统资源类,用于访问文件系统中的文件。发送邮件时,调用`mailSender.send()`方法即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值