자바 메 일의 시 뮬 레이 션 전송 실현

2986 단어 자바
package com.mollen.utils;

import org.junit.Test;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @ClassName:      SendMail
 * @Auther:         Mollen
 * @CreateTime:     2018-10-17  23:56:36
 * @Description:
 *                         :
 *                  qq    :      
 */
public class SendMailUtils {

    /**
     * 1.      
     */
    private static Properties props;                        //      
    private static InternetAddress sendMan = null;          //      
    private static String userName = "[email protected]";      //         
    private static String password = "pijwmdxjijejdehf";        //       (   )

    //    
    static {
        props = new Properties();
        props.put("mail.transport.protocol", "smtp");  //     
        props.put("mail.smtp.host", "smtp.qq.com");    //    smtp.qq.com
        props.put("mail.smtp.port", 25);               //   
        props.put("mail.smtp.auth", "true");           //       
        //props.put("mail.debug", "true");               //     

        try {
            //      
            sendMan = new InternetAddress(userName);
        } catch (AddressException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 2.          
     *
     */
    public static void sendMail(String to ,String title,String text) throws AddressException, MessagingException {

            Session session = Session.getInstance(props);    //       
            MimeMessage msg = new MimeMessage(session);      //       

            msg.setFrom(sendMan);                            //      
            msg.setRecipients(Message.RecipientType.TO,to);  //        
            msg.setSubject(title);                           //   
            msg.setSentDate(new Date());                     //     
            msg.setContent(text, "text/html;charset=UTF-8"); //     

            //   
            try{
                Transport trans = session.getTransport();
                trans.connect(userName, password);
                trans.sendMessage(msg, msg.getAllRecipients());
                System.out.println("    ...");
                trans.close();
            }catch(Exception e){
                System.out.println("    ...");
                e.printStackTrace();
            }
    }

    @Test
    public void  test(){
        try {
            SendMailUtils.sendMail("[email protected]","       ","Hello Mail!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

원문:https://blog.csdn.net/mollen/article/details/83177595

좋은 웹페이지 즐겨찾기