如何使用java发送邮件

最近,我们在写一个旅游网站的小项目,就此次项目,我在这里做一个小小的总结

项目实现的功能有:
用户注册:用户名异步加载(用户名不能重复),发送邮件,用户的激活;
用户登录:验证码校验,自动登陆,根据用户登录状态显示不同的错误信息
异步加载导航条:旅游路线的分类显示
点击导航条分页显示所属类的所有旅游航线:分页显示
搜索分页显示所有旅游航线:模糊查询,分页显示,异步加载显示下拉框
旅游航线的详细页面:操作数据库,添加收藏,表关联关系
用户收藏页面的分页展示:分页显示
我会陆陆续续将本次项目中出现的问题总结出来,做一个总结和思考

1.发送邮件:
用户注册成功发送邮件:我们之前在网上商城案例中已经使用过发送邮件的功能,但在这次的项目中,发现发送邮件端口号25绑定异常,去网上搜索相关资料并未发现很好的解决办法,于是去网上搜素相关的java发送邮件的相关代码时,意外发现比之前更好用的发送邮件方法:SendMailThread.java,有兴趣的同学可以去下载此工具类,只要我们开启了邮箱的第三方登录权限,就可以使用该邮箱往任意邮箱发送邮件啦!
我在此以我自己的qq邮箱为例,手把手教大家怎么用自己邮箱发送邮件!非常简单!
具体步骤如下:
工具类准备(不知道怎么上传java文件,只能将代码贴出来啦):

package cn.itheima.travel.util;

import java.security.GeneralSecurityException;
import java.util.Properties;

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

import com.sun.mail.util.MailSSLSocketFactory;

public class SendMailThread extends Thread {
    private String mailAdr;
    private String content;
    private String subject;

    public static void sendEmail(String email, String code) {
        String zhuti = "来自黑马旅游商城的激活邮件!";
        String content = "<h1>来自黑马旅游商城的激活邮件:请点击下面链接激活!</h1><h3><a href='http://localhost:8080/activeUser?code="
                + code
                + "'>http://localhost:8080/activeUser?code="
                + code
                + "</a></h3>";
        SendMailThread d = new SendMailThread(email, zhuti, content);
        d.start();
    }

    public SendMailThread(String mailAdr, String subject, String content) {
        // TODO Auto-generated constructor stub
        super();
        this.mailAdr = mailAdr;
        this.subject = subject;
        this.content = content;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        try {
            sendMail(mailAdr, subject, content);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void sendMail(String mailAdr, String subject, String content)
            throws Exception {
        // TODO Auto-generated method stub
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);

        final Properties props = new Properties();
        // 表示SMTP发送邮件,需要进行身份验证
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
        // 端口
        /* props.put("mail.smtp.port", 25); */
        // smtp登陆的账号、密码 ;需开启smtp登陆
        props.setProperty("mail.debug", "true");
        //修改下面两个地方
        props.put("mail.user", "这里是你的邮箱账号");
        props.put("mail.password", "你的授权码");
        // 特别需要注意,要将ssl协议设置为true,否则会报530错误
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);

            }
        };
        // 使用环境属性和授权信息,创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        try {
            InternetAddress form = new InternetAddress(
                    props.getProperty("mail.user"));
            message.setFrom(form);

            // 设置收件人
            InternetAddress to = new InternetAddress(mailAdr);
            message.setRecipient(RecipientType.TO, to);

            // 设置抄送
            // InternetAddress cc = new InternetAddress("[email protected]");
            // message.setRecipient(RecipientType.CC, cc);

            // 设置密送,其他的收件人不能看到密送的邮件地址
            // InternetAddress bcc = new InternetAddress("[email protected]");
            // message.setRecipient(RecipientType.CC, bcc);

            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */
    /*
     * public static void main(String[] args) { // TODO Auto-generated method
     * stub SendMailThread d = new SendMailThread("[email protected]",
     * "hahahah", "测试邮件001 <br>今天学习了怎么发送邮件</br>"); d.start();
     * 
     * }
     */

}

开启邮箱的第三方登录权限
1.打开qq邮箱<设置>
2.点击<账户>
3.开启pop3/smtp服务(默认是关闭的)
4.按照提示发送一条短信
5.我们会收到一个授权码,复制授权码,一会用(授权码不是唯一的,忘记了可以再生成一个,再发一次上面短信就行了)
6.最关键的一步,在我们的工具类中,修改我提示的两个地方:将邮箱改成你需要发送邮件的发送端邮箱,授权码改成你刚刚粘贴的
7.最后,我们就可以传入一个邮箱账号和激活码直接调用sendEmail方法发送邮件啦!当然,邮件的主题和内容,大家可以根据自己的项目需要自行修改啦
ps:最后需要注意的一点,在ssh框架中我们不需要导入jar包就可以使用该类,但如果我们是在普通的java项目中使用该工具类,需要导入一个mail.jar包,大家可以去网上搜索下载,下载好导入也可以发送邮件了!

猜你喜欢

转载自blog.csdn.net/caiyibing1992/article/details/81738430