当前位置:   article > 正文

Java发送邮件(带附件)_java发送邮件带附件

java发送邮件带附件

pom依赖

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

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; //收件人
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

发送邮件方法业务类

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 != filePath && !"".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());
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/591830
推荐阅读
相关标签
  

闽ICP备14008679号