发送邮件

来源:互联网 发布:网络体彩 编辑:程序博客网 时间:2024/06/15 23:31

导包: * mail.jar * actvition.jar
配置文件:email_template.properties
内容:

subject=\u6765\u81EA\u7F51\u4E0A\u4E66\u57CE\u7684\u6FC0\u6D3B\u90AE\u4EF6content=\u606D\u559C\uFF0C\u60A8\u5DF2\u6CE8\u518C\u6210\u529F\uFF0C\u8BF7\u70B9\u51FB<a href\="http\://localhost\:/sgoods/UserServlet?method\=activation&activationCode\={0}">\u8FD9\u91CC</a>\u5B8C\u6210\u6FC0\u6D3B\u3002from=m12312347850@163.comhost=smtp.163.comusername=m12312347850password=xxx

代码:

//注册public void regist(User user){        /*         * 数据补齐         */        user.setUid(CommonUtils.uuid());        user.setStatus(false);        user.setActivationCode(CommonUtils.uuid()+CommonUtils.uuid());        /*         * 向数据库插入         */        try {            userDao.add(user);        } catch (SQLException e) {            throw new RuntimeException(e);        }        /*         * 发邮件         */        /*         * 把配置文件加载到prop中         */        Properties prop=new Properties();        try {            prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));        } catch (IOException e) {            throw new RuntimeException(e);        }        /*         * 登录服务器,得到session         */        String host=prop.getProperty("host");//服务器主机名        String name=prop.getProperty("username");//登录名        String pass=prop.getProperty("password");//登录密码        Session session=MailUtils.createSession(host, name, pass);        /*         * 创建Mail对象         */        String from=prop.getProperty("from");        String to=user.getEmail();        String subject=prop.getProperty("subject");        //MessageFormat.format   方法会把第一个参数中的{0},用第二个参数来替换        //MessageFormat.format("你好 {0},你好 {1}","张三","李四");  返回"你好 张三,你好 李四'        String content=MessageFormat.format(prop.getProperty("content"), user.getActivationCode());        Mail mail=new Mail(from,to,subject,content);        /*         * 发送邮件         */        try {            MailUtils.send(session, mail);        } catch (MessagingException e) {            throw new RuntimeException(e);        } catch (IOException e) {            throw new RuntimeException(e);        }    }/**     * 激活功能     * @param activationCode     * @throws UserException      */    public void activation(String activationCode) throws UserException {        /*         * 通过激活码查询用户         * 如果User为null ,无效激活,抛出异常(无效激活码)         * 查看用户状态,如果为true,抛出异常(请不要二次激活)         * 修改 用户状态为true         */        try {            User user=userDao.findByActivation(activationCode);            if(user==null){                throw new UserException("无效激活码");            }else if(user.isStatus()){                throw new UserException("请不要二次激活");            }            userDao.updateStatus(user.getUid(),true);        } catch (SQLException e) {            throw new RuntimeException(e);        }    }

JavaMail

1 JavaMail概述
Java Mail是由SUN公司提供的专门针对邮件的API,主要Jar包:mail.jar、activation.jar。
在使用MyEclipse创建web项目时,需要小心!如果只是在web项目中使用java mail是没有什么问题的,发布到Tomcat上运行一点问题都没有!
但是如果是在web项目中写测试那就出问题了。
在MyEclipse中,会自动给web项目导入javax.mail包中的类,但是不全(其实是只有接口,而没有接口的实现类),所以只靠MyEclipse中的类是不能运行java mail项目的,但是如果这时你再去自行导入mail.jar时,就会出现冲突。
处理方案:到下面路径中找到javaee.jar文件,把javax.mail删除!!!
D:\Program Files\MyEclipse\Common\plugins\com.genuitec.eclipse.j2eedt.core_10.0.0.me201110301321\data\libraryset\EE_5

2 JavaMail中主要类
java mail中主要类:javax.mail.Session、javax.mail.internet.MimeMessage、javax.mail.Transport。
Session:表示会话,即客户端与邮件服务器之间的会话!想获得会话需要给出账户和密码,当然还要给出服务器名称。在邮件服务中的Session对象,就相当于连接数据库时的Connection对象。
MimeMessage:表示邮件类,它是Message的子类。它包含邮件的主题(标题)、内容,收件人地址、发件人地址,还可以设置抄送和暗送,甚至还可以设置附件。
Transport:用来发送邮件。它是发送器!

3 JavaMail之Hello World
在使用telnet发邮件时,还需要自己来处理Base64编码的问题,但使用JavaMail就不必理会这些问题了,都由JavaMail来处理。
第一步:获得Session
Session session = Session.getInstance(Properties prop, Authenticator auth);
其中prop需要指定两个键值,一个是指定服务器主机名,另一个是指定是否需要认证!我们当然需要认证!
Properties prop = new Properties();
prop.setProperty(“mail.host”, “smtp.163.com”);//设置服务器主机名
prop.setProperty(“mail.smtp.auth”, “true”);//设置需要认证

其中Authenticator是一个接口表示认证器,即校验客户端的身份。我们需要自己来实现这个接口,实现这个接口需要使用账户和密码。
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication () {
new PasswordAuthentication(“itcast_cxf”, “itcast”);//用户名和密码
}
};
通过上面的准备,现在可以获取得Session对象了:
Session session = Session.getInstance(prop, auth);

第二步:创建MimeMessage对象
创建MimeMessage需要使用Session对象来创建:
MimeMessage msg = new MimeMessage(session);
然后需要设置发信人地址、收信人地址、主题,以及邮件正文。
msg.setFrom(new InternetAddress(“itcast_cxf@163.com”));//设置发信人
msg.addRecipients(RecipientType.TO, “itcast_cxf@qq.com,itcast_cxf@sina.com”);//设置多个收信人
msg.addRecipients(RecipientType.CC, “itcast_cxf@sohu.com,itcast_cxf@126.com”);//设置多个抄送
msg.addRecipients(RecipientType.BCC, ”itcast_cxf@hotmail.com”);//设置暗送
msg.setSubject(“这是一封测试邮件”);//设置主题(标题)
msg.setContent(“当然是hello world!”, “text/plain;charset=utf-8”);//设置正文

第三步:发送邮件
Transport.send(msg);//发送邮件

4 JavaMail发送带有附件的邮件(了解)
一封邮件可以包含正文、附件N个,所以正文与N个附件都是邮件的一个部份。
上面的hello world案例中,只是发送了带有正文的邮件!所以在调用setContent()方法时直接设置了正文,如果想发送带有附件邮件,那么需要设置邮件的内容为MimeMultiPart。
MimeMulitpart parts = new MimeMulitpart();//多部件对象,可以理解为是部件的集合
msg.setContent(parts);//设置邮件的内容为多部件内容。
然后我们需要把正文、N个附件创建为“主体部件”对象(MimeBodyPart),添加到MimeMuiltPart中即可。
MimeBodyPart part1 = new MimeBodyPart();//创建一个部件
part1.setCotnent(“这是正文部分”, “text/html;charset=utf-8”);//给部件设置内容
parts.addBodyPart(part1);//把部件添加到部件集中。

下面我们创建一个附件:
MimeBodyPart part2 = new MimeBodyPart();//创建一个部件
part2.attachFile(“F:\a.jpg”);//设置附件
part2.setFileName(“hello.jpg”);//设置附件名称
parts.addBodyPart(part2);//把附件添加到部件集中

注意,如果在设置文件名称时,文件名称中包含了中文的话,那么需要使用MimeUitlity类来给中文编码:
part2.setFileName(MimeUitlity.encodeText(“美女.jpg”));

原创粉丝点击