邮件的发送

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;



@Slf4j
@Service("sendMailMessageService")
public class SendMailMessageServiceImpl {


    /**
     * 发送消息
     */
    @Override
    public void sendMail(MailMessageDTO messageDTO) throws MessageException {
        if (null != messageDTO) {
            // 获取发件邮件配置
            MailHost mailHost = messageDTO.getMailHost();
            // 发送邮件名称
            String userName = mailHost.getUserName();
            // 发送邮件密码
            String passWord = mailHost.getPassword();
            // 邮件服务器
            String host = mailHost.getHost();
            // 是否需要鉴权
            boolean needAuth = mailHost.isNeedAuth();

            // 获取接收邮件地址
            String[] toAddressArray = messageDTO.getToAddress();
            if (null == toAddressArray || toAddressArray.length <= 0) {
                log.error("接收人邮件信息为空,请检查。");
                throw new MessageException(ResultCodeMessageType.JOB_COPIES_CONFIRM_SEND_MAIL_TOADDRESS);
            }

            // 获取发送附件
            Vector<File> file = messageDTO.getFile();
            // 获取邮件服务器session
            Session session = getSession(mailHost, host, needAuth);

            Transport trans = null;
            Message msg = new MimeMessage(session);
            try {
                // 设置邮件发送人信息
                Address from_address = new InternetAddress(mailHost.getUserName(), messageDTO.getSenderName());
                msg.setFrom(from_address);

                InternetAddress[] address = new InternetAddress[toAddressArray.length];
                for (int i = 0; i < toAddressArray.length; i++) {
                    address[i] = new InternetAddress(toAddressArray[i]);
                }

                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setSubject(messageDTO.getTitle());
                Multipart mp = new MimeMultipart();
                MimeBodyPart mbp = new MimeBodyPart();
                mbp.setContent(messageDTO.getContent(), "text/html;charset=gb2312");
                mp.addBodyPart(mbp);
                // 是否有附件,如有附件则将附件添加到邮件中  
                if (!file.isEmpty()) {
                    Enumeration<File> efile = file.elements();
                    String filePath = null;
                    while (efile.hasMoreElements()) {
                        mbp = new MimeBodyPart();
                        // 选择出每一个附件名  
                        filePath = efile.nextElement().toString();
                        // 得到数据源
                        FileDataSource fds = new FileDataSource(filePath);
                        // 得到附件本身并至入BodyPart
                        mbp.setDataHandler(new DataHandler(fds));

                        // 得到文件名同样至入BodyPart
                        String fileName = new String(fds.getName().getBytes(), CodingTypeEnum.ISO88591.getName());
                        mbp.setFileName(fileName);
                        mp.addBodyPart(mbp);
                    }
                    file.removeAllElements();
                }
                // Multipart加入到信件  
                msg.setContent(mp);
                // 设置信件头的发送日期  
                msg.setSentDate(new Date());
                // 发送信件  
                msg.saveChanges();
                trans = session.getTransport("smtp");
                trans.connect(host, userName, passWord);
                trans.sendMessage(msg, msg.getAllRecipients());

                log.info(messageDTO.getTitle() + ",发送成功。");
            } catch (UnsupportedEncodingException e) {
                log.error("发送邮件失败。", e);
                throw new MessageException(ResultCodeMessageType.JOB_COPIES_CONFIRM_MAIL_ERROR);
            } catch (MessagingException e) {
                log.error("发送邮件失败。", e);
                throw new MessageException(ResultCodeMessageType.JOB_COPIES_CONFIRM_MAIL_ERROR);
            } finally {
                if (null != trans) {
                    try {
                        trans.close();
                    } catch (MessagingException e) {
                        log.error("邮件流关闭异常", e);
                    }
                }
            }
        }
    }

    /**
     * 获取发送邮件服务器session
     * 
     * @param mailHost
     * @param host
     * @param needAuth
     * @return
     */
    private Session getSession(MailHost mailHost, String host, boolean needAuth) {
        Session session = null;
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(needAuth));
        if (needAuth) {
            SmtpAuth smtpAuth = new SmtpAuth(mailHost.getUserName(), mailHost.getPassword());
            session = Session.getDefaultInstance(props, smtpAuth);
        } else {
            session = Session.getDefaultInstance(props, null);
        }

        // 设置为:true,打印发送邮件信息日志,便于开发人员观察(生产环境设置为false)
        session.setDebug(false);
        return session;
    }

   

}
public class MailHost {

    private String  host;

    private int     port;

    private String  auth;

    private String  transportProtocol;

    private String  userName;

    private String  password;

    private boolean needAuth;
}

import java.io.File;
import java.io.Serializable;
import java.util.Vector;

import lombok.Data;


@Data
public class MailMessageDTO implements Serializable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 4023036129951405601L;

    /**
     * 邮件配置信息对象
     */
    private MailHost          mailHost;

    /**
     * 邮件附件
     */
    private Vector<File>      file;

    /**
     * 发送邮件内容
     */
    private String            content;

    /**
     * 邮件标题
     */
    private String            title;

    /**
     * 接收邮件地址
     */
    private String[]          toAddress;

    /**
     * 发件人名称
     */
    private String            senderName;
}

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;


public class SmtpAuth extends Authenticator {
    /**
     * 用户名
     */
    private String userName;

    /**
     * 登录密码
     */
    private String passWord;

    public SmtpAuth(String username, String password) {
        this.userName = username;
        this.passWord = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, passWord);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值