码迷,mamicode.com
首页 > 编程语言 > 详细

使用JavaMail API发送邮件

时间:2014-10-27 12:38:07      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   使用   java   

发送邮件是很常用的功能,注册验证,找回密码,到货通知,欠费提醒等,都可以通过邮件来提醒。

Java中发送邮件需要使用javax.mail.jar包,读者可以上网搜索或去官方下载,下载地址为:

下面贴上发送邮件的核心代码。

 1 // Get system properties
 2         Properties properties = System.getProperties();
 3 
 4         // Setup mail server
 5         properties.setProperty("mail.smtp.host", host);
 6         properties.setProperty("mail.smtp.port", port);
 7         properties.put("mail.smtp.auth", "true");
 8 
 9         // create email authenticator.
10         Authenticator authenticator = new Authenticator() {
11             protected PasswordAuthentication getPasswordAuthentication() {
12                 return new PasswordAuthentication(username, password);
13             }
14         };
15 
16         // Get the default Session object.
17         Session session = Session.getDefaultInstance(properties, authenticator);
18 
19         try {
20             // Create a default MimeMessage object.
21             MimeMessage message = new MimeMessage(session);
22 
23             // Set From: header field of the header.
24             message.setFrom(new InternetAddress(from));
25 
26             // Set To: header field of the header.
27             for (String to : toList) {
28                 message.addRecipient(Message.RecipientType.TO,
29                         new InternetAddress(to));
30             }
31 
32             // Set Subject: header field
33             message.setSubject("这是邮件标题", "utf-8");58 
59             // Send the complete message parts
60             message.setContent("这里是邮件内容", "text/html;charset=utf-8");
61 
62             // Send message
63             Transport.send(message);
64             System.out.println("Sent message successfully....");
65         } catch (MessagingException mex) {
66             mex.printStackTrace();67         }

 

我自己定义了一个类EmailSender,这个类提供了邮件群发功能,以及在邮件中发送附件。用户继承这个类,重载getSubject,getContent和getAttachments这三个方法便可以发送邮件。

类定义如下:

package com.iot.common.email;

import java.io.File;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.Multipart;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeBodyPart;

import javax.mail.BodyPart;

import javax.mail.PasswordAuthentication;

import javax.mail.Authenticator;

import java.util.ArrayList;

import javax.mail.MessagingException;

import javax.mail.Transport;

import javax.mail.Message;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.Session;

import java.util.Properties;

import java.util.List;

/**
 * 邮件发送类,用来发送邮件给用户.<br />
 * 
 * @author Sam
 * 
 */
public abstract class EmailSender extends Authenticator {

    private String host;
    private String port;
    private String username;
    private String password;
    private String from;

    public EmailSender() {
        this.host = PropertiesUtil.getProperty(Constant.EMAIL_HOST);
        this.port = PropertiesUtil.getProperty(Constant.EMAIL_HOST_PORT);
        this.username = PropertiesUtil.getProperty(Constant.EMAIL_USER_NAME);
        this.password = PropertiesUtil.getProperty(Constant.EMAIL_PASSWORD);
        this.from = PropertiesUtil.getProperty(Constant.EMAIL_SENDER);
    }

    /**
     * EmailSender构造函数,需要用户提供host,port,username,password,from等信息。<br />
     * 
     * @param host
     *            ,smtp服务器地址
     * @param port
     *            ,smtp服务器端口
     * @param username
     *            ,邮箱用户名
     * @param password
     *            ,邮箱密码
     * @param from
     *            ,邮箱发送人
     */
    public EmailSender(String host, String port, String username,
            String password, String from) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.from = from;
    }

    /**
     * 发送邮件到指定用户
     * 
     * @param to
     *            , 邮件发送对象
     * @return ture 发送成功, false发送失败
     */
    public Boolean send(String to) {

        List<String> toList = new ArrayList<>();
        toList.add(to);

        return send(toList);
    }

    /**
     * 群发邮件
     * 
     * @param toList
     *            ,需要接受邮件的用户
     * @return ture 发送成功, false发送失败
     */
    public Boolean send(List<String> toList) {

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");

        // create email authenticator.
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties, authenticator);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            for (String to : toList) {
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(to));
            }

            // Set Subject: header field
            message.setSubject(getSubject(), "utf-8");

            // Create the message part
            BodyPart messageBodyPart = new MimeBodyPart();

            // Fill the message
            messageBodyPart.setContent(getContent(), "text/html;charset=utf-8");

            // Create a multipar message
            Multipart multipart = new MimeMultipart();

            // Set text message part
            multipart.addBodyPart(messageBodyPart);

            // add attachment
            List<File> attchments = getAttachments();
            if (attchments != null && attchments.size() > 0) {
                for (File attachment : attchments) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(attachment);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachment.getName());
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            // Send the complete message parts
            message.setContent(multipart);

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();

            return false;
        }

        return true;
    }

    /**
     * 获取邮件主题,支持html格式。
     * 
     * @return
     */
    protected abstract String getSubject();

    /**
     * 获取邮件内容,支持html格式。
     * 
     * @return
     */
    protected abstract String getContent();

    /**
     * 获取附件列表,若不需要发送附件,请返回null或长度为0的List<File>列表.<br />
     * 
     * @return
     */
    protected abstract List<File> getAttachments();

}

 

与邮件发送服务器相关信息存储在properties.xml文件中,文件结构如下:

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>邮件系统配置文件</comment>

    <entry key="EMAIL_HOST">smtp.126.com</entry>

    <entry key="EMAIL_HOST_PORT">25</entry>

    <entry key="EMAIL_USER_NAME"><username>@126.com</entry>

    <entry key="EMAIL_PASSWORD"><password></entry>

    <entry key="EMAIL_SENDER"><username>@126.com</entry>
</properties>

 

 

PropertiesUtil类用于读取properties.xml文件中的属性,代码如下:

/**
 * 
 */
package com.iot.common.email;

import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

/**
 * @author Sam <br />
 * 读取properties信息 <br />
 * 
 */
public class PropertiesUtil {

    /**
     * Get property by name
     * 
     * @param name
     * @return
     */
    public static String getProperty(String name) {
        return properties.getProperty(name);
    }

    private static Properties properties;

    /****
     * Initialize properties
     */
    static {
        String filePath = "properties.xml";
        InputStream stream = PropertiesUtil.class.getClassLoader()
                .getResourceAsStream(filePath);

        properties = new Properties();

        try {
            properties.loadFromXML(stream);
        } catch (InvalidPropertiesFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

静态常量类Contanst代码如下:

package com.iot.common.email;

/**
 * 
 * @author Lynn
 * 
 *         Store all constant field
 * 
 */
public class Constant {

    /* email sending information */
    public static final String EMAIL_HOST = "EMAIL_HOST";
    public static final String EMAIL_HOST_PORT = "EMAIL_HOST_PORT";
    public static final String EMAIL_USER_NAME = "EMAIL_USER_NAME";
    public static final String EMAIL_PASSWORD = "EMAIL_PASSWORD";
    public static final String EMAIL_SENDER = "EMAIL_SENDER";

}

 

测试代码如下:

 1 package com.iot.common.email;
 2 
 3 import java.io.File;
 4 
 5 import java.util.ArrayList;
 6 
 7 import java.util.List;
 8 
 9 public class EmailTest {
10 
11     /**
12      * @param args
13      */
14     public static void main(String[] args) {
15         // TODO Auto-generated method stub
16 
17         EmailSender sender = new EmailSender() {
18 
19             @Override
20             protected String getSubject() {
21                 // TODO Auto-generated method stub
22                 return "测试邮件,请不要回复";
23             }
24 
25             @Override
26             protected String getContent() {
27                 // TODO Auto-generated method stub
28                 return "<h1>尊敬的用户:</h1><br /><p>这是一封测试邮件,请不要恢复改邮件!</p>";
29             }
30 
31             @Override
32             protected List<File> getAttachments() {
33                 // TODO Auto-generated method stub
34                 
35                 List<File> files=new ArrayList<>();
36                 files.add(new File("d:/district.txt"));
37                 files.add(new File("d:/test2.jar"));
38                 
39                 return files;
40             }
41         };
42 
43         List<String> to = new ArrayList<>();
44         to.add("409253645@qq.com");
45         to.add("sam@steperp.com");
46         to.add("hui@126.com");
47 
48         sender.send(to);
49 
50     }
51 
52 }

 

使用JavaMail API发送邮件

标签:style   blog   http   io   color   os   ar   使用   java   

原文地址:http://www.cnblogs.com/samzeng/p/4053870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!