简单实现邮件发送

2018-08-18 14:33 更新
  1. 用maven构建一个java项目

2.发送邮件的核心jia包:

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

3.配置文件config.properties,代码如下:

#############Email Server Config#################
EMAIL.EMAIL_HOST=smtp.163.com
EMAIL.TRANSPORT_PROTOCOL=smtp
EMAIL.SMTP_AUTH=true
EMAIL.EMAIL_FROM=www@163.COM
EMAIL.EMAIL_USER=wwww
EMAIL.EMAIL_PWD=123456
#############Email Server Config#################
######### email #########
esb.email=xxxxxx@qq.com;aaaaaaa@qq.com

4.读取配置文件类:Config.java:

public class Config
{
public static ThreadPoolExecutor SendPoolExecutor = new ThreadPoolExecutor(10, 50, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    private static Properties properties = PropertiesUtil.getProperties("properties/config.properties");
    private static String emailHost;
    private static String emailFrom;
    private static String emailUser;
    private static String emailPwd;
    private static String smtpAuth;
    private static String transportProtocol;
    static{
        emailHost=properties.getProperty("EMAIL.EMAIL_HOST");
        emailFrom=properties.getProperty("EMAIL.EMAIL_FROM");
        emailUser=properties.getProperty("EMAIL.EMAIL_USER");
        emailPwd=properties.getProperty("EMAIL.EMAIL_PWD");
        smtpAuth=properties.getProperty("EMAIL.TRANSPORT_PROTOCOL");
        transportProtocolproperties.getProperty("EMAIL.SMTP_AUTH");
    }


    public static Properties getProperties()
    {
        return properties;
    }
.......
}

5.创建邮件配置发送类:MailUtil

public class MailUtil
{
    private static Logger logger = Logger.getLogger(MailUtil.class);
    public static void sendEamil(List<InternetAddress> addresses, List<InternetAddress> ccAddresses, String topic, String context)
    {
        try
        {
            Properties props = System.getProperties();
            props.put("mail.smtp.host", Config.getEmailHost());
            props.put("mail.smtp.auth", Config.getSmtpAuth);
            Multipart multipart = new MimeMultipart();
            MimeBodyPart bodyPart = new MimeBodyPart();
            String contentType = "text/html; charset=UTF-8";

            
            multipart.addBodyPart(bodyPart);
            Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(MsgConfig.getEmailFrom()));
            InternetAddress[] addArray = (InternetAddress[]) addresses.toArray(new InternetAddress[0]);
            message.addRecipients(Message.RecipientType.TO, addArray);
            if ( null!=ccAddresses&& ccAddresses.size() > 0)
            {
                message.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[0])); // 抄送人 
            }
            message.setSubject(topic,"UTF-8");
            bodyPart.setContent(context , contentType);
            message.setContent(multipart);
            Transport transport = session.getTransport("smtp");
            transport.connect(MsgConfig.getEmailHost(), MsgConfig.getEmailUser(), MsgConfig.getEmailPwd());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("sendEmail is succeed.");
        }
        catch (Exception e)
        {
            logger.info("sendEmail is error.", e);
            throw new EmailException(e.getMessage(), e);
        }
    }
    public static void main(String[] args) {

        
        try {
            List<InternetAddress> addresses=new ArrayList<InternetAddress>(); 
            InternetAddress addresses1=new InternetAddress("xxxxx@163.com");
            addresses.add(addresses1);
            MailUtil.sendEamil(addresses, null, "内容", "呢绒");
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

6.创建一个新的进程去发送邮件:SendEmailNewThread

public class SendEmailNewThread implements Runnable {
    private static Logger logger = Logger.getLogger(SendEmailNewThread.class);
    private List<InternetAddress> emailList;
    private Map<String,String> message;
    public SendEmailNewThread(List<InternetAddress> emailList,  Map<String,String> message) {
        this.emailList = emailList;
        this.message = message;
    }
    @Override
    public void run() {
        String topic = message.get("topic");
        String context = message.get("context");
        if(emailList.size()>0){
            MailUtil.sendEamil(emailList, null, topic, context);
            logger.info("send email to:"+emailList+" success!");
        }
    }
}

7.调用测试:Test

public static void main(String[] args){
    String email = Config.getEmail();
    String[] emails = email.split(CommonConstant.SPLIT);
    List<InternetAddress> emailList = new ArrayList<InternetAddress>();
    Map<String, String> message = new HashMap<String, String>();
    message.put("topic", "xxx提醒");
    message.put("context", "已xxxxx"+itemgroupout+",请相关人员在srm系统维护数据和权限。");
    for(int i=0; i<emails.length; i++){
        InternetAddress indr = new InternetAddress(emails[i]);
        emailList.add(indr);
    }
    Config.SendPoolExecutor.execute(new SendEmailNewThread(emailList, message));
}

完结。

简洁版:

package cyh.util;


import java.util.Date;
import java.util.Properties;


import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


import org.apache.log4j.Logger;


public class EmailUtil {
    /**
     * 发送邮件
     * @param email
     * @param code
     * @return
     */
    public static boolean sendEmail(String email, String code) {
        Logger logger=Logger.getLogger(EmailUtil.class);
        boolean result=false;
        Properties pop = new Properties();
        pop.setProperty("mail.debug", "true");
        pop.setProperty("mail.smtp.auth", "true");
        pop.setProperty("mail.host", "smtp.163.com");
        pop.setProperty("mail.transport.protocol", "smtp");


        Session session = Session.getInstance(pop);


        Message msg = new MimeMessage(session);
        try {
            msg.setSubject("Traveling Man Mailbox verification");
            msg.setText(setMessage(email,code));
            msg.setFrom(new InternetAddress("redriverhong@163.com"));


            Transport ts = session.getTransport();


            ts.connect("redriverhong", "xxxxxx");
            ts.sendMessage(msg, new Address[] { new InternetAddress(email) });
            ts.close();
            result=true;
            logger.info("邮件发送成功!");
        } catch (MessagingException e) {
            e.printStackTrace();
            result=false;
            logger.error("邮件发送失败。");
        }
        return result;
    }


    public static String setMessage(String email,String code) {
        Date date = new Date();
        StringBuffer sb = new StringBuffer();
        sb.append("您好:").append("\n");
        sb.append("感谢您注册旅途人网站!你的注册邮箱是:").append(email).append("\n");
        sb.append("您注册的验证码是:").append(code).append("\n");
        sb.append("该验证码在20分钟内有效,20分钟后需要重新注册。").append("\n");
        sb.append(date);
        return sb.toString();
    }


    public static void main(String args[]) throws MessagingException {
        sendEmail("redriverhong@163.com", "xxxxxx");
    }
}

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号