1. 程式人生 > >Java傳送郵件的幾種方式

Java傳送郵件的幾種方式

最近的一個專案中用到了郵件傳送,所以研究了一下。將其總結下來。
要傳送郵件就要用到java中的JavaMail,關於JavaMailAPI的詳解呢在
(http://blog.csdn.net/imain/article/details/1453677“)中有非常詳盡的介紹,我就直接上程式碼了。
1:使用JavaMail傳送郵件

 // 1.建立一個程式與郵件伺服器會話物件 Session
 Properties props = new Properties();
 props.setProperty("mail.transport.protocol", "SMTP");
 props.setProperty("mail.smtp.host"
, "smtp.163.com"); props.setProperty("mail.smtp.port", "25"); // 指定驗證為true props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.timeout","1000"); // 驗證賬號及密碼,密碼需要是第三方授權碼 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication({ return
new PasswordAuthentication("*******@163.com", "*******"); } }; Session session = Session.getInstance(props, auth); // 2.建立一個Message,它相當於是郵件內容 Message message = new MimeMessage(session); // 設定傳送者 message.setFrom(new InternetAddress("*******@163.com")); // 設定傳送方式與接收者 message.setRecipient(MimeMessage.RecipientType.TO, new
InternetAddress(email)); // 設定主題 message.setSubject("郵件傳送測試"); // 設定內容 message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.建立 Transport用於將郵件傳送 Transport.send(message);

2:我用的是spring框架,spring 封裝了一個簡單易用的關於郵件傳送的工具類JavaMailSenderImpl ,所以可以用JavaMailSenderImpl 來實現郵件傳送。

public class MailService {
    private static final String HOST = "smtp.163.com";
    private static final Integer PORT = 25;
    private static final String USERNAME = "*******@163.com";
    private static final String PASSWORD = "*******";
    private static final String EMAILFORM = "*******@163.com";
    private static JavaMailSenderImpl mailSender = createMailSender();
    /**
     * 郵件傳送器
     *
     * @return 配置好的工具
     */
    private static JavaMailSenderImpl createMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(HOST);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout", "25000");
        p.setProperty("mail.smtp.auth", "false");
        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 傳送郵件
     *
     * @param to 接受人
     * @param subject 主題
     * @param html 傳送內容
     * @throws MessagingException 異常
     * @throws UnsupportedEncodingException 異常
     */
    public static void sendHtmlMail(String to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 設定utf-8或GBK編碼,否則郵件會有亂碼
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(EMAILFORM, "系統名稱");
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        mailSender.send(mimeMessage);
    }
}

當然這種是硬編碼的方式了。也可以寫在資原始檔中。

資原始檔

mailConfig.properties
#伺服器
mailHost=smtp.163.com
#埠號
mailPort=25
#郵箱賬號
mailUsername=*******@163.com
#郵箱授權碼
mailPassword=*******
#時間延遲
mailTimeout=25000
#傳送人
mailFrom=*******@163.com

獲得資原始檔內容

public class MailConfig {
    private static final String PROPERTIES_DEFAULT = "mailConfig.properties";
    public static String host;
    public static Integer port;
    public static String userName;
    public static String passWord;
    public static String emailForm;
    public static String timeout;
    public static String personal;
    public static Properties properties;
    static{
        init();
    }

    /**
     * 初始化
     */
    private static void init() {
        properties = new Properties();
        try{
            InputStream inputStream = MailConfig.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT);
            properties.load(inputStream);
            inputStream.close();
            host = properties.getProperty("mailHost");
            port = Integer.parseInt(properties.getProperty("mailPort"));
            userName = properties.getProperty("mailUsername");
            passWord = properties.getProperty("mailPassword");
            emailForm = properties.getProperty("mailFrom");
            timeout = properties.getProperty("mailTimeout");
            personal = "墨裔";
        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

傳送郵件

public class MailUtil {
    private static final String HOST = MailConfig.host;
    private static final Integer PORT = MailConfig.port;
    private static final String USERNAME = MailConfig.userName;
    private static final String PASSWORD = MailConfig.passWord;
    private static final String emailForm = MailConfig.emailForm;
    private static final String timeout = MailConfig.timeout;
    private static final String personal = MailConfig.personal;
    private static JavaMailSenderImpl mailSender = createMailSender();
    /**
     * 郵件傳送器
     *
     * @return 配置好的工具
     */
    private static JavaMailSenderImpl createMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(HOST);
        sender.setPort(PORT);
        sender.setUsername(USERNAME);
        sender.setPassword(PASSWORD);
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout", timeout);
        p.setProperty("mail.smtp.auth", "false");
        sender.setJavaMailProperties(p);
        return sender;
    }

    /**
     * 傳送郵件
     *
     * @param to 接受人
     * @param subject 主題
     * @param html 傳送內容
     * @throws MessagingException 異常
     * @throws UnsupportedEncodingException 異常
     */
    public static void sendMail(String to, String subject, String html) throws MessagingException,UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 設定utf-8或GBK編碼,否則郵件會有亂碼
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(emailForm, personal);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(html, true);
        mailSender.send(mimeMessage);
    }
}