java发送邮件

package com.wonder.util;

import com.wonder.entity.EmailDto;
import org.apache.log4j.Logger;

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

public class EmailUtil {
    public static Logger log = Logger.getLogger(EmailUtil.class);
    //发送邮件
    public static Map<String,String> sendEmail(EmailDto emailDto){
        Map<String,String> resultMap=new HashMap<>();
        resultMap.put("status","1");
        resultMap.put("msg","发送成功");
        if(emailDto.getSubject()==null || emailDto.getSubject().equals("")){
            log.error("邮件主题不能为空");
            resultMap.put("status","0");
            resultMap.put("msg","邮件主题不能为空,发送失败");
        }
        if(emailDto.getContent()==null || emailDto.getContent().equals("")){
            log.error("邮件内容不能为空");
            resultMap.put("status","0");
            resultMap.put("msg","邮件内容不能为空,发送失败");
        }
        try {
            final Properties props = new Properties();
            String fileName=emailDto.getFilename();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host",EmailPropertity.MAIL_HOST);
            props.put("mail.smtp.port", EmailPropertity.MAIL_PORT);
            // 发件人的账号
            props.put("mail.user", EmailPropertity.EMAIL_USER);
            // 访问SMTP服务时需要提供的密码
            props.put("mail.password", EmailPropertity.EMAIL_PWD);
            // 如果使用ssl,则去掉使用25端口的配置,进行如下配置,
            if (EmailPropertity.ENABLE_SSL == EmailPropertity.SSL_ENABLE_TRUE ) {
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.socketFactory.port", EmailPropertity.MAIL_PORT);
                props.put("mail.smtp.port", EmailPropertity.MAIL_PORT);
            }
            // 构建授权信息,用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息,创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            MimeMessage mailMessage = new MimeMessage(mailSession);
            mailMessage.setFrom(new InternetAddress(EmailPropertity.SERVER_ADDRESS, MimeUtility.encodeText(EmailPropertity.SERVER_NAME, "UTF-8", "b")));
            //发送邮件接收人
            if(emailDto.getToUserEmailList()!=null){
                String[] toEmailArr= new String[emailDto.getToUserEmailList().size()];
                emailDto.getToUserEmailList().toArray(toEmailArr);
                mailMessage.setRecipients(MimeMessage.RecipientType.TO, formatString(toEmailArr));
            }
            //发送邮件抄送人
            if(emailDto.getCcUserEmailList()!=null){
                String[] ccEmailArr= new String[emailDto.getCcUserEmailList().size()];
                emailDto.getCcUserEmailList().toArray(ccEmailArr);
                mailMessage.setRecipients(MimeMessage.RecipientType.CC, formatString(ccEmailArr));
            }
            //发送文件
            if(emailDto.getFile()!=null && !emailDto.getFile().isEmpty()){
                if(fileName==null || fileName.equals("")){
                    log.error("文件名不能为空");
                    resultMap.put("status","0");
                    resultMap.put("msg","文件名不能为空,发送失败");
                }
                Multipart mp = new MimeMultipart();
                MimeBodyPart mbpContent = new MimeBodyPart();
                mbpContent.setText(emailDto.getContent());
                mp.addBodyPart(mbpContent);
                /* 往邮件中添加附件 */
                Enumeration<String> efile = emailDto.getFile().elements();
                while (efile.hasMoreElements()) {
                    MimeBodyPart mbpFile = new MimeBodyPart();
                    fileName = efile.nextElement().toString();
                    FileDataSource fds = new FileDataSource(fileName);
                    mbpFile.setDataHandler(new DataHandler(fds));
                    mbpFile.setFileName(toChinese(fds.getName()));
                    mp.addBodyPart(mbpFile);
                    mailMessage.setContent(mp);
                }
                log.info("附近添加成功");
            }else{
                //发送内容
                mailMessage.setContent(toChinese(emailDto.getContent()), "text/html;charset=UTF-8");
            }
            //发送主题
            mailMessage.setSubject(toChinese(emailDto.getSubject()));
            Transport.send(mailMessage);
        }catch (Exception e){
            log.error("邮件发送失败,异常原因:"+e.getMessage());
            resultMap.put("status","0");
            resultMap.put("msg","发送失败");
        }
        return resultMap;
    }

    public  static void main(String args[]) {
        Map<String,String> resultMap=new HashMap<>();
        List<String>  touserEmailList =new ArrayList<String>();
        touserEmailList.add("23442432934@qq.com");
        //touserEmailList.add("4324399837@qq.com");
        List<String>  ccUserEmailList =new ArrayList<String>();
        ccUserEmailList.add("yangyu@ec.cn");
        EmailDto emailDto=new EmailDto();
        emailDto.setSubject("yangyu");
        emailDto.setContent("nihao");
        emailDto.setToUserEmailList(touserEmailList);
        emailDto.setCcUserEmailList(ccUserEmailList);

        String fileName = "nihao";
        String fileName1="D://DMLS_DDL.txt";
        String fileName2="D://yy.txt";
        Vector<String> files=new Vector<>();
        files.add(fileName1);
        files.add(fileName2);
        emailDto.setFile(files);
        emailDto.setFilename(fileName);
        resultMap =sendEmail(emailDto);
        log.info(resultMap.get("msg"));
    }
    /*****
     *
     * @Title: formatString
     * @Description: 将数组相应的地址
     * @param address
     * @return
     * @return: InternetAddress[]
     */
    private static InternetAddress[] formatString(String... address) {
        InternetAddress[] internetAddresses = new InternetAddress[address.length];
        List<InternetAddress> list = new ArrayList<InternetAddress>(address.length);
        for (String str : address) {
            try {
                list.add(new InternetAddress(str));
            } catch (AddressException e) {
                e.printStackTrace();
            }
        }
        return list.toArray(internetAddresses);
    }

    public static String toChinese(String text) {
        try {
            text = MimeUtility.encodeText(new String(text.getBytes(), "UTF-8"), "UTF-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }
}




package com.wonder.entity;

import java.util.List;
import java.util.Vector;

public class EmailDto {
    //邮件接收者
    private List<String> toUserEmailList;
    //邮件抄送者
    private List<String> ccUserEmailList;
    //邮件主题
    private String subject;
    //邮件内容
    private String content;
    //附件
    private Vector<String> file;
    // 附件的文件名
    private String filename;

    public List<String> getToUserEmailList() {
        return toUserEmailList;
    }

    public void setToUserEmailList(List<String> toUserEmailList) {
        this.toUserEmailList = toUserEmailList;
    }

    public List<String> getCcUserEmailList() {
        return ccUserEmailList;
    }

    public void setCcUserEmailList(List<String> ccUserEmailList) {
        this.ccUserEmailList = ccUserEmailList;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Vector<String> getFile() {
        return file;
    }

    public void setFile(Vector<String> file) {
        this.file = file;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }
}



package com.wonder.util;

public class EmailPropertity {

    //主机名
    public static String  MAIL_HOST="smtp.163.com";

    //端口号
    public static int MAIL_PORT=25;

    // 发件人的账号
    public static String EMAIL_USER="139@163.com";

   // 访问SMTP服务时需要提供的密码
    public static String EMAIL_PWD="58.";

    //服务地址
    public static String SERVER_ADDRESS="139@163.com";

    //服务名称(自定义)
    public static String SERVER_NAME="会飞的鱼";

    public static int ENABLE_SSL=0;

    public static final int SSL_ENABLE_TRUE = 1;
}




 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值