javaMail发送邮件实例

 Mailer类的说明:

具有两个构造函数

  • Mailer() 读取properties文件的数据配置javamail的发送属性
  • Mailer(String mail_host, String stmp_port, String template_file_path, String send_from, String pw, String charset) 使用参数配置javamail的发送属性
  • sendMail()发送邮件主函数
  • getTemplate()从服务器指定路径读取以存文件作为发送邮件的content

环境配置说明:

必须引入的两个开发包:mail.jar  activation.jar

可能出现的错误说明:

  • 缺少activation.jar系统会报Exception in thread "Thread-1" java.lang.NoClassDefFoundError: javax/activation/DataSource异常
  • 在用户名和密码都没有问题的情况下,如果代码抛出javax.mail.AuthenticationFailedException异常,先用OutLook测试一下看能否进行正常的收发邮件,有时信箱如果是新注册的话,邮件的服务商默认刚注册的帐号是不能使用pop3的。例如126.com在我进行代码测试时,刚刚注册的帐号是没有权限使用该功能的,所以就会抛出上述的异常。
    还有,要注意from的email地址和Authenticator类中验证的用户名是一致的,要不也会出错

Mailer.java

/*---------Operating instructions----edit by lynn at 20080319 
 * Make a JSP file like this:
 * <%@ page import="mailer.*"%>
    <%
    Mailer mailer = new Mailer();
    //In Mailer class,you can use a template file for the mail content by the method of getTemplate().
    String content = Mailer.getTemplate("MemberApplyFirst.txt");
            
    mailer.sendMail("yehell@hotmail.com", "test", content ,"VOGUE");

    Mailer mail = new Mailer("gmail-smtp.l.google.com","25","E://test//","lynn.yehell@gmail.com","password","utf-8");
    mail.sendMail("yehell@hotmail.com", "test", content ,"VOGUE");
    %>
*/

package  mailer;

import  java.io.BufferedReader;
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.IOException;
import  java.io.InputStreamReader;
import  java.util.ArrayList;
import  java.util.Date;
import  java.util.HashMap;
import  java.util.Properties;
import  java.util.ResourceBundle;

import  javax.mail.Authenticator;
import  javax.mail.Message;
import  javax.mail.MessagingException;
import  javax.mail.PasswordAuthentication;
import  javax.mail.Session;
import  javax.mail.Transport;
import  javax.mail.internet.AddressException;
import  javax.mail.internet.InternetAddress;
import  javax.mail.internet.MimeMessage;

public   class  Mailer  {
    
private static ResourceBundle bundle;

    
private static String TEMPLATE_FILE_PATH;

    
private static String MAIL_HOST;
    
    
private static String SMTP_PORT;

    
private static String USER_NAME;

    
private static String USER_PASSWORD;

    
private static String SEND_FROM;
    
    
private static String MAIL_CHARSET;

    
private Properties props;

    
private Session session;

    
private MimeMessage msg;

    
private static HashMap templates;

    
public Mailer() {
        
super();
        
//Get the data of properties file
        try {
            
if (bundle == null{
                bundle 
= ResourceBundle.getBundle("mail_config");
                TEMPLATE_FILE_PATH 
= bundle.getString("TEMPLATE_FILE_PATH");
                MAIL_HOST 
= bundle.getString("MAIL_HOST");
                SMTP_PORT 
= bundle.getString("SMTP_PORT");
                USER_NAME 
= bundle.getString("USER_NAME");
                USER_PASSWORD 
= bundle.getString("USER_PASSWORD");
                SEND_FROM 
= bundle.getString("SEND_FROM");
                MAIL_CHARSET 
= bundle.getString("MAIL_CHARSET");
            }

        }
 catch (Exception e) {
            e.printStackTrace();
        }

        bundle 
= null;

        
// Get a Properties object
        this.props = System.getProperties();
        props.setProperty(
"mail.smtp.host", MAIL_HOST );
        props.setProperty(
"mail.smtp.port", SMTP_PORT );
        props.setProperty(
"mail.smtp.socketFactory.port", SMTP_PORT );
        props.put(
"mail.smtp.socketFactory.fallback""true" );
        props.put(
"mail.transport.protocol""smtp" );
        props.put(
"mail.smtp.starttls.enable""true" );
        props.put(
"mail.smtp.auth""true" );
//        props.put("mail.smtp.socketFactory.class", "javax.net.SocketFactory");

        
this.session = Session.getInstance(props, new Authenticator() {
            
protected PasswordAuthentication getPasswordAuthentication() {
                
return new PasswordAuthentication(USER_NAME, USER_PASSWORD);
            }

        }
);
        
//this.session.setDebug(true);
        this.msg = new MimeMessage(session);
    }

    
public Mailer(String mail_host, String stmp_port, String template_file_path, String send_from, String pw, String charset) {
        
super();

        TEMPLATE_FILE_PATH 
= template_file_path;
        SEND_FROM 
= send_from;
        USER_NAME 
= send_from;
        USER_PASSWORD 
= pw;
        MAIL_CHARSET 
= charset;
        
//         Get a Properties object
        this.props = System.getProperties();
        props.setProperty(
"mail.smtp.host", mail_host );
        props.setProperty(
"mail.smtp.port", stmp_port );
        props.setProperty(
"mail.smtp.socketFactory.port", stmp_port );
        props.put(
"mail.smtp.socketFactory.fallback""true" );
        props.put(
"mail.transport.protocol""smtp" );
        props.put(
"mail.smtp.starttls.enable""true" );
        props.put(
"mail.smtp.auth""true" );
//        props.put("mail.smtp.socketFactory.class", "javax.net.SocketFactory");

        
this.session = Session.getInstance(props, new Authenticator() {
            
protected PasswordAuthentication getPasswordAuthentication() {
                
return new PasswordAuthentication(USER_NAME, USER_PASSWORD);
            }

        }
);
        
this.session.setDebug(true);
        
this.msg = new MimeMessage(session);
    }


    
public void sendMail(String to, String title, String content, String site)throws Exception {
        
try {
            msg.setFrom(
new InternetAddress(SEND_FROM , SEND_FROM.substring(0,SEND_FROM.indexOf("@"))));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, 
false));
            msg.setSubject(title, MAIL_CHARSET );
            msg.setText(content);
            msg.setSentDate(
new Date());
            Transport.send(msg);
        }
 catch (AddressException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
            
throw new Exception(e);
        }
 catch (MessagingException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
            
throw new Exception(e);
        }
 catch (Exception e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
            
throw new Exception(e);
        }

    }


    
public static String getMailContent(String template, ArrayList params) {
        String strReturn 
= template;
        
for (int i = params.size(); i > 0; i--{
            strReturn 
= strReturn.replaceAll("%" + (i), params.get(i - 1).toString());
        }

        
return strReturn;
    }


    
public static String getTemplate(String fileName) throws Exception {
        
if (templates == null{
            templates 
= new HashMap();
        }

        
if (templates.get(fileName) != null{
            
return templates.get(fileName).toString();
        }
 else {
            String filepath 
= TEMPLATE_FILE_PATH + fileName;
            File file 
= new File(filepath);
            String returnStr 
= "";
            
if (file.isFile()) {
                
try {
                    InputStreamReader read 
= new InputStreamReader(new FileInputStream(file), MAIL_CHARSET);

                    BufferedReader bReader 
= new BufferedReader(read);

                    String line;

                    
while ((line = bReader.readLine()) != null{
                        returnStr 
+= line;
                        returnStr 
+= " ";
                    }

                }
 catch (FileNotFoundException e) {
                    e.printStackTrace();
                    
throw new Exception(e);
                }
 catch (IOException e) {
                    e.printStackTrace();
                    
throw new Exception(e);
                }

                templates.put(fileName, returnStr);
            }

            
return returnStr;
        }

    }

}

 mail_config.properties 文件(该文件必须放在classes目录下才能被读取)

TEMPLATE_FILE_PATH  =  E: // test //
MAIL_HOST 
=  gmail-smtp . l . google . com
SMTP_PORT 
=   25
MAIL_CHARSET 
=   SHIFT -JIS

USER_NAME 
=  guofeng . matest@gmail . com
USER_PASSWORD 
=  maguofeng1
SEND_FROM 
=  guofeng . matest@gmail . com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值