天天看点

JavaMail邮件发送JavaMail邮件发送

JavaMail邮件发送

1、导入mail.jar,mail-api.jar。

2、JavaMail工具类代码:

public class JavaMail {

  /**
     * Message对象将存储我们实际发送的电子邮件信息,
     * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。
     */
    private MimeMessage message;
    
    /**
     * Session类代表JavaMail中的一个邮件会话。
     * 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。
     * 
     * JavaMail需要Properties来创建一个session对象。
     * 寻找"mail.smtp.host"    属性值就是发送邮件的主机
     * 寻找"mail.smtp.auth"    身份验证,目前免费邮件服务器都需要这一项
     */
    private Session session;
    
    /***
     * 邮件是既可以被发送也可以被接受。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。 
     * Transport 是用来发送信息的,而Store用来收信。这里只需要用到Transport对象。
     */
    private Transport transport;
    
    private String mailHost="ismtp.beyondsoft.com";//服务器地址
    private int mailport=465;//端口
    private String sender_username="[email protected]";//用户名
    private String sender_password="xiebin0220141222";//密码
    private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//指定ssl的工厂
    
    private Properties properties = new Properties();
    
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    
 /**
  * 初始化方法
  * @throws IOException 
  */
 public JavaMail(boolean debug) throws IOException {
 
 InputStream in = JavaMail.class.getClassLoader().getResourceAsStream("empcare.properties");
 properties.load(in);
 this.mailHost = properties.getProperty("mail.smtp.host");
        this.mailport = Integer.parseInt(properties.getProperty("mail.smtp.port"));
        this.sender_username = properties.getProperty("mail.send.username");
        this.sender_password = properties.getProperty("mail.send.password");
 this.SSL_FACTORY = properties.getProperty("mail.smtp.socketFactory.class");
 
 Properties props = new Properties();  
 
 // 指定SMTP服务器
     props.put("mail.smtp.host", this.mailHost);  
     props.put("mail.smtp.port", String.valueOf(this.mailport));  
     props.put("mail.smtp.starttls.enable","true");
     
     // 指定是否需要SMTP验证
     props.put("mail.smtp.auth", "true");  
     
     // If you need to authenticate
     // Use the following if you need SSL
     //添加安全权限
     Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
     props.put("mail.smtp.socketFactory.port", String.valueOf(this.mailport)); // 指定SMTP ssl服务器
     props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
     props.put("mail.smtp.socketFactory.fallback", "false");
     props.put("mail.smtp.ssl.protocols", properties.getProperty("mail.smtp.ssl.protocols"));
     
 session = Session.getDefaultInstance(props, new Authenticator(){  

 protected PasswordAuthentication getPasswordAuthentication() {  

 return new PasswordAuthentication(sender_username, sender_password);  

 }}); 

 //session = Session.getDefaultInstance(properties);
 session.setDebug(debug);//开启后有调试信息
 message = new MimeMessage(session);
 }
 
 /**
     * 发送邮件
     * 
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUser
     *            收件人地址
     */
    @SuppressWarnings("static-access")
 public boolean doSendHtmlEmail(String subject, String sendHtml,String receiveUser) {
     
     boolean res=true;
        try {
         
            // 发件人
            //InternetAddress from = new InternetAddress(sender_username);
            // 下面这个是设置发送人的Nick name
            InternetAddress from = new InternetAddress(" <"+sender_username+">");
            message.setFrom(from);
            
            // 收件人
            InternetAddress to = new InternetAddress(receiveUser);
            message.setRecipient(Message.RecipientType.TO, to);//还可以有CC、BCC
            
            // 邮件主题
            message.setSubject(subject);
            
            String content = sendHtml.toString();
            
            // 邮件内容,也可以使纯文本"text/plain"
            message.setContent(content,"text/html;charset=UTF-8");
            
            // 保存邮件
            message.saveChanges();
            
            //第一种方式
            //transport = session.getTransport("smtp");
            // smtp验证,就是你用来发邮件的邮箱用户名密码
            //transport.connect(mailHost,mailport,sender_username, sender_password);
            // 发送
            //transport.sendMessage(message, message.getAllRecipients());
            
            //第二种方式
            transport.send(message);
            
            System.out.println("send success!");
        } catch (Exception e) {
            e.printStackTrace();
            res=false;
        }finally {
            if(transport!=null){
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }
    
    /**
     * 发送多人邮件
     * 
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUsers
     *            收件人地址
     */
    public boolean doSendHtmlEmail(String subject, String sendHtml,String [] receiveUsers) {
     
     boolean res=true;
        try {
            // 发件人
            //InternetAddress from = new InternetAddress(sender_username);
            // 下面这个是设置发送人的Nick name
            InternetAddress from = new InternetAddress(" <"+sender_username+">");
            message.setFrom(from);
            
            // 收件人
            Address[] address =new InternetAddress[receiveUsers.length];
            for (int i = 0; i < receiveUsers.length; i++) {
           address[i]=new InternetAddress(receiveUsers[i]);
            }
            
            message.setRecipients(Message.RecipientType.TO, address);//还可以有CC、BCC
            
            // 邮件主题
            message.setSubject(subject);
            
            String content = sendHtml.toString();
            // 邮件内容,也可以使纯文本"text/plain"
            message.setContent(content, "text/html;charset=UTF-8");
            
            // 保存邮件
            message.saveChanges();
            
            transport = session.getTransport("smtp");
            // smtp验证,就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost,mailport,sender_username, sender_password);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());
            
            System.out.println("send success!");
        } catch (Exception e) {
            e.printStackTrace();
            res=false;
        }finally {
            if(transport!=null){
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }
    
    public static void main(String[] args) throws MessagingException, IOException {
        JavaMail se = new JavaMail(true);
        String [] test={"[email protected]","[email protected]"};
        se.doSendHtmlEmail("主题", "<h1>内容</h1>", "[email protected]");
    }
}
           

3、当然还需要配置下配置文件

mail.smtp.host=

mail.smtp.port=

mail.send.username=

mail.send.password=

mail.smtp.socketFactory.port=

mail.smtp.socketFactory.class=

mail.smtp.ssl.protocols=