Java发送邮件(带附件)

Posted 胡乐天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java发送邮件(带附件)相关的知识,希望对你有一定的参考价值。

pom依赖

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

EmailInfo实体类

package com.lt.bus.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class EmailInfo 

    private String host; //邮箱服务器主机
    private String port; //邮件服务器端口
    private String from; //发件人
    private String password; //授权码
    private String nickname; //发件人昵称
    private String subject; //邮件主题
    private String content; //邮件内容
    private String filePath; //附件路径,邮件可写多个,以|分割
    private String address; //收件人


发送邮件方法业务类

package com.lt.bus.service.impl;

import com.lt.bus.pojo.EmailInfo;
import com.lt.bus.pojo.ResultMessage;
import com.lt.bus.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

@Service
public class EmailServiceImpl implements EmailService 

    Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Override
    public ResultMessage sendEmail(EmailInfo emailInfo) 

        Properties properties = new Properties();
        properties.put("mail.smtp.host",emailInfo.getHost());
        properties.put("mail.smtp.auth","true");
        Session session = Session.getInstance(properties);
        Message emailMessage = new MimeMessage(session);

        try 
            //发送人
            InternetAddress sender = new InternetAddress(emailInfo.getFrom()); //发送者账号
            sender.setPersonal(MimeUtility.encodeText(emailInfo.getNickname()));//昵称
            emailMessage.setFrom(sender);

            //收件人
            InternetAddress to = new InternetAddress(emailInfo.getAddress());//收件人账号
            emailMessage.setRecipient(Message.RecipientType.TO,to);

            //消息
            emailMessage.setSubject(MimeUtility.encodeText(emailInfo.getSubject()));//邮件主题
            emailMessage.setSentDate(new Date());
            MimeMultipart mimeMultipart = new MimeMultipart("mixed");//指定为混合关系
            emailMessage.setContent(mimeMultipart);

            //邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(emailInfo.getContent(),"text/html;charset=UTF-8");

            //组装内容
            mimeMultipart.addBodyPart(htmlPart);

            //组装附件
            String filePath = emailInfo.getFilePath();
            if(null != null && !"".equals(filePath))
                //ToDo 此处可携带多个附件,以|分割****************
                if(filePath.indexOf("|")<0)
                    MimeBodyPart file = new MimeBodyPart();
                    FileDataSource file_datasource = new FileDataSource(filePath);
                    DataHandler dh = new DataHandler(file_datasource);
                    file.setDataHandler(dh);
                    //附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码
                    file.setFileName(MimeUtility.encodeText(dh.getName()));
                    mimeMultipart.addBodyPart(file);
                else
                    String[] filePaths = filePath.split("\\\\|");
                    for(int i=0;i<filePaths.length;i++)
                        MimeBodyPart file = new MimeBodyPart();
                        FileDataSource file_datasource = new FileDataSource(filePaths[i]);
                        DataHandler dh = new DataHandler(file_datasource);
                        file.setDataHandler(dh);
                        //附件区别内嵌内容的一个特点是有文件名,为防止中文乱码要编码
                        file.setFileName(MimeUtility.encodeText(dh.getName()));
                        mimeMultipart.addBodyPart(file);
                    
                
            

            emailMessage.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(emailInfo.getHost(), Integer.parseInt(emailInfo.getPort()),emailInfo.getFrom(), emailInfo.getPassword());
            transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
            transport.close();
            return ResultMessage.ok("邮件发送成功!");
         catch (AddressException e) 
            logger.error("邮件发送失败,错误原因:"+e.getMessage());
            return ResultMessage.error("请检查邮箱地址:"+e.getMessage());
         catch (UnsupportedEncodingException e) 
            logger.error("邮件发送失败,错误原因:"+e.getMessage());
            return ResultMessage.error("转码异常,请查看详细信息"+e.getMessage());
         catch (NoSuchProviderException e) 
            logger.error("邮件发送失败,错误原因:"+e.getMessage());
            return ResultMessage.error("邮件发送失败,详细错误原因:"+e.getMessage());
        catch (MessagingException e) 
            logger.error("邮件发送失败,错误原因:"+e.getMessage());
            return ResultMessage.error("邮件发送失败,有可能的问题为服务器url不存在或附件不存在,具体请看详细信息:"+e.getMessage());
        
    


以上是关于Java发送邮件(带附件)的主要内容,如果未能解决你的问题,请参考以下文章

Java发送邮件(带附件)

紧急求助,关于java 取domino的附件

[Java] JavaMail 发送带图片的 html 格式的邮件

用java写一个邮件发送代码

java发送邮件失败!

GMAIL API 在 C# 中发送带附件的电子邮件