使用JavaMail发送邮件
使用JavaMail发送邮件
酷游博客

使用JavaMail发送邮件

酷游
1月22日发布 /正在检测是否收录...

使用JavaMail的API发送邮件~!

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.List;

/**
 * Created by hollis on 15/8/30.
 */
@Service
public class MailService {
    private final String MAIL_SMTP_HOST="smtp.*****.com";
    private final String MAIL_SMTP_PORT="465";//465端口是为SMTPS(SMTP-over-SSL)协议服务开放的
    private final String MAIL_SENDER_MAIL="****@alibaba-inc.com";
    private final String MAIL_SENDER_PASS="****";
    private final String MAIL_SENDER_NICKNAME="****平台";
    private Logger logger = Logger.getLogger(MailService.class);

    public static void main(String[] args) {
        MailService m = new MailService();
        List recipients = new ArrayList();
        l.add("***@alibaba-inc.com");

        List copyToRecipients = new ArrayList();
        l1.add("***@alibaba-inc.com");

        try {
            m.sendMail("title","content",recipients,copyToRecipients,null);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Session
     * @return
     */
    private Session getMailSession(){
        Properties props = new Properties();

        props.put("mail.smtp.host", MAIL_SMTP_HOST);
        props.put("mail.smtp.port", MAIL_SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MAIL_SENDER_MAIL, MAIL_SENDER_PASS);
            }
        });

        return session;
    }

    /**
     *
     * @param title 邮件标题
     * @param content  邮件内容
     * @param recipients 收件人邮箱列表
     * @param copyToRecipients 抄送人邮箱列表
     * @param secretCopyToRecipients 密送人邮箱列表
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public boolean sendMail(String title,String content,Collection recipients,
                          Collection copyToRecipients,Collection secretCopyToRecipients) throws AddressException, MessagingException, UnsupportedEncodingException {
        // 初始化收件人、抄送、密送邮箱列表
        List toAddresses = parseStringToAddress(recipients);
        List ccAddresses = parseStringToAddress(copyToRecipients);
        List bccAddresses = parseStringToAddress(secretCopyToRecipients);
        //初始化邮件内容
        Message message = new MimeMessage(getMailSession());
        message.setFrom(new InternetAddress(MAIL_SENDER_MAIL, MAIL_SENDER_NICKNAME));
        String subject = MimeUtility.encodeWord(title, "UTF-8", "Q");//设置标题编码
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        // 收件人
        message.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()]));

        // 抄送
        message.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));

        // 密送
        message.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));

        message.saveChanges();

        Transport.send(message);

        return true;//不报异常表示邮件发送成功
    }

    /**
     * 将字符串类型的邮箱地址转成InternetAddress类型的邮箱地址
     * @param mailStrings
     * @return List
     */
    private List parseStringToAddress(Collection mailStrings) throws AddressException {

        if(CollectionUtils.isEmpty(mailStrings)){
            return Collections.emptyList();
        }
        List addressList = new ArrayList();

        for(String mailString:mailStrings){
            InternetAddress internetAddress =  new InternetAddress(mailString);
            addressList.add(internetAddress);
        }
        return addressList;
    }

}

相关链接:Could not connect to SMTP host: smtp.***.com, port: 465, response: -1

© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 赞赏
评论
当前页面的评论已关闭
易航博客
SSL