Java实现发送邮件并携带附件

一、 邮件服务器与传输协议

要在网络上实现邮件功能,必须要有专门的邮件服务器。主要负责接收用户投递过来的邮件,并把邮件投递到邮件接收者的电子邮箱中。

  • SMTP服务器地址:一般是 smtp.xxx.com,163邮箱是smtp.163.com,qq邮箱是smtp.qq.com。
  • SMTP协议
    • 通常把处理用户smtp请求(邮件发送请求)的服务器称之为SMTP服务器(邮件发送服务器)。
  • POP3协议
    • 通常把处理用户pop3请求(邮件接收请求)的服务器称之为POP3服务器(邮件接收服务器)。

 

二、 在发送人邮箱中开启POP3/SMTP服务

  • qq邮箱
    • 登录qq邮箱后 → 设置 → 账户 → POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 → POP3/SMTP服务点击开启(需要绑定手机号发送验证短信)→ 获得了一串授权码(后续发送邮件需要)
  • 163邮箱
    • 登录163邮箱 → 设置 → POP3/SMTP/IMAP → POP3/SMTP服务 点击开启(需要邮箱app认证) → 获取到一串授权码

 

 三、 导入依赖

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

 四、 编写工具类

import lombok.extern.slf4j.Slf4j;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;

@Slf4j
public class EmailUtils {
    public static final String SenderEmail = "xxxxx@qq.com";//发送人邮箱
    public static final String senderCode = "ixxxxxxxxxxxdcd";//发送人邮箱授权码
    public static final String emailSMTPHost = "smtp.qq.com";//服务器地址

    public static final String receiveMailAccount = "xxxxx@qq.com";//收件人邮箱
    public static final String ccMailAccount = "xxxxx@163.com";//抄送人邮箱
    public static final String bccmailAccount = "xxxxxx@qq.com";//密送人邮箱

    /*发送邮件*/
    public static void sendMail() {
        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);//获取邮件对象(封装了一个方法)

            Transport transport = session.getTransport();

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

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

            // 7. 关闭连接
            transport.close();

            log.info("邮件发送成功");
        } catch (Exception e) {
            log.error("发送邮件失败");
        }

    }
    



    public static MimeMessage createMimeMessage(Session session) throws Exception {
        // 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(receiveMailAccount, "收件人", "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("这是邮件的主题", "UTF-8");

        // 5. Content: 邮件正文(可以使用html标签)
        message.setContent("这是邮件正文", "text/html;charset=UTF-8");

*****************以下部分为携带附件代码,不需要携带附件的可删除星号圈起的部分*************************
        MimeMultipart multipart = new MimeMultipart();
        MimeBodyPart file1 = new MimeBodyPart();
        DataHandler handler = new DataHandler(new FileDataSource("文件路径"));
        file1.setDataHandler(handler);
        //对文件名进行编码,防止出现乱码
        String fileName = MimeUtility.encodeWord("文件名", "utf-8", "B");
        file1.setFileName(fileName);
        multipart.addBodyPart(file1);
        message.setContent(multipart);
*******************************************************************************************

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

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

        return message;
    }
}

五、 最后

  • 在同时设置正文和附件时,导致发送邮件后正文不显示,请大佬们指点。

 

你可以使用JavaMail API来发送附件的电子邮件。以下是一个示例代码,展示了如何使用Java Servlet发送附件的邮件: ```java import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; // 邮件服务器的配置信息 final String username = "your_email@example.com"; final String password = "your_email_password"; final String smtpHost = "smtp.example.com"; final int smtpPort = 587; // 发件人和收件人的电子邮件地址 String fromEmail = "from@example.com"; String toEmail = "to@example.com"; // 创建一个会话对象 Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // 创建一个默认的MimeMessage对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(fromEmail)); // 设置收件人 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); // 设置主题 message.setSubject("邮件主题"); // 创建一个Multipart对象,用于存储邮件的各个部分 Multipart multipart = new MimeMultipart(); // 创建邮件正文部分 BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("邮件正文"); multipart.addBodyPart(messageBodyPart); // 创建附件部分 messageBodyPart = new MimeBodyPart(); String filename = "path_to_attachment_file"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // 将Multipart对象设置为邮件内容 message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("邮件发送成功"); } catch (MessagingException e) { e.printStackTrace(); } ``` 请将代码中的 `your_email@example.com`,`your_email_password`,`smtp.example.com`,`from@example.com`,`to@example.com` 和 `path_to_attachment_file` 替换为你自己的实际信息。 这段代码使用了JavaMail API来创建一个MimeMessage对象,并设置了发件人、收件人、主题和邮件正文。然后,创建了一个Multipart对象,并向其中添加了邮件正文部分和附件部分。最后,将Multipart对象设置为邮件内容,通过Transport类的send()方法发送邮件。 确保你的项目中包含了JavaMail API的相关依赖,并在Servlet的web.xml文件中配置好Servlet的映射和相关参数。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值