使用Java发送邮件

情景:使用java发送邮件验证码

利用java发送邮件需要做一些准备操作:

这里使用到了qq邮箱。

首先,打开qq邮箱,在设置,帐户那里,开启pop3/smtp,和imap/smtp服务。这里开启需要手机发送短信来验证。

而后,点击下方得生成授权码,会要求使用手机来验证。验证ok后,会生成一串授权码,记住它,后面有用。使用java mail来利用qq邮箱发送邮件就需要这个授权码。(这里有个需要注意得点是:这个16位的授权码显示的时候是4个4个一组得显示,但是,实际上,授权码是16位连续的,中间没有空格,这个在后面输入的时候要注意!,要不然会报535错误!)

使用java来使用mail服务,需要相应的包,这个包有3个,在我的上传资源里可以找到。

接下来上代码就完事了:

 



import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JavaMailUtil {
    //发件人的邮箱和密码
    public static String emailAccount="qq邮箱地址";
    //发件人的邮箱得授权码
    public static String emailPassword="授权码";
    //发件人邮箱得服务地址
    public static String emailSMTPHost="smtp.qq.com";
    //收件人邮箱
    public static String receiveMailAccount="";

    /**
     * 创建一封邮件对象
     * @param session
     * @param sendMail
     * @param receiveMail
     * @param html
     * @return
     * cc:抄送
     * Bcc:密送
     * To:发送
     */
    public static MimeMessage createMimeMessage(Session session,String sendMail,String receiveMail,String html) throws UnsupportedEncodingException, MessagingException {
        //创建一封邮件对象
        MimeMessage message = new MimeMessage(session);
        //From:发件人
        message.setFrom(new InternetAddress(sendMail,"发送方的名字","utf-8"));
        //To:收件人(也可以抄送或者密送)
        message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(receiveMail,"对方name","utf-8"));
        //Subject:邮件的主题
        message.setSubject("邮箱验证","utf-8");
        //content:邮件正文(可以使用html标签)
        message.setContent(html,"text/html;charset=UTF-8");
        //设置发送时间
        message.setSentDate(new Date());
        //保存设置
        message.saveChanges();
        return message;
    }
}

还需要一个类来生成随机数: 

 



import java.lang.ref.SoftReference;

public class RandomUtil {
    public static String getRandom(){
        String[]letters=new String[]{"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m",
                "A","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M",
                "0","1","2","3","4","5","6","7","8","9"
              };
        String code="";
        for(int i=0;i<6;i++)
        {
            code=code+letters[(int)Math.floor(Math.random()*letters.length)];
        }
        return code;
    }
}


public class htmlText {
    public static String sendHtml(String code)
    {
        String html="Email地址验证<br/>"+
                "这封邮件是快拼网发送的。<br/>"+
                "你收到的这封邮件是csdn进行新用户注册的。<br/>"+
                "账号激活声明<br/>"+
                "请将下面的验证码输入提示框里即可!"+
                "<h3 style='color:red;'>"+code+"</h3><br/>";
        return html;
    }

}

 这是邮件的内容。

使用的时候:

 @RequestMapping("sendEmail")
    @ResponseBody
    public String sendEmail(String email, HttpSession httpSession){
        JavaMailUtil.receiveMailAccount=email;//给用户输入的邮箱发送邮件
        //1.创建参数配置,用来连接邮箱服务器的参数配置
        Properties props = new Properties();
        //开启Debug模式
        props.setProperty("mail.debug","true");
        //发送服务器需要身份验证
        props.setProperty("'mail.smtp.auth","true");
        //设置邮件服务器的主机名
        props.setProperty("mail.host",JavaMailUtil.emailSMTPHost);
        //发送邮件协议名称
        props.setProperty("mail.transport.protocol","smtp");
        //2.根据配置创建会话对象用来和邮件服务器交互
        Session session = Session.getInstance(props);
        //设置debug,可以查看详细的发送log
        session.setDebug(true);
        //3.创建一封邮件
        String code = RandomUtil.getRandom();
        System.out.println("邮箱验证码:"+code);
        String html = htmlText.sendHtml(code);
        MimeMessage message=null;
        try {
            message= JavaMailUtil.createMimeMessage(session, JavaMailUtil.emailAccount, JavaMailUtil.receiveMailAccount, html);
            //4.根据session获取邮件传输对象
            Transport transport = session.getTransport();
            //5.使用邮箱账号和密码连接邮件服务器emailAccount必须和message中的发件人一样,否则报错
            transport.connect(JavaMailUtil.emailAccount,JavaMailUtil.emailPassword);
            //6.发送邮件,发送所有收件人的地址
            transport.sendMessage(message,message.getAllRecipients());
            //7.关闭连接
            transport.close();
            //写入session
            httpSession.setAttribute("code",code);
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
        return "OK";
    }
    @RequestMapping("register")
    public String register(Register register,HttpSession httpSession){
        String code =(String) httpSession.getAttribute("code");
        System.out.println(code);
        if(code!=null)
        {
            //获取页面提交的验证码
            String inputCode = register.getCode();
            System.out.println("页面提交的验证码"+inputCode);
            if(code.toLowerCase().equals(inputCode.toLowerCase()))
            {
                //验证成功,暂时先跳转到这里
                return "customer";
            }

        }
        //移除验证码
        httpSession.removeAttribute("code");
//验证失败,暂时先跳转到这里
        return "login";
    }

这样就OK了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.email.send; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class EmailSender { String protocol ="smtp"; //服务器 String from="*******@qq.com";//寄信人,这里可以改为你的邮箱地址 String to="*******@qq.com";//收信人,改为你要寄给那人的邮箱地址 建议可以用自己的QQ邮箱试试 String subject="Java发送邮件测试!";//邮件主题 String body="<a href=http://www.qq.com>qq.com" + "</a><br><img src=\"cid:8.jpg\">";//邮件内容 这是一个HTTP网页类的邮件内容 public static void main(String []args)throws Exception{ String server ="smtp.qq.com";//QQ邮箱的服务器,例如新浪邮箱或者其他服务器可以自己去查,这里用QQ邮箱为例 String user="******@qq.com";//登录邮箱的用户,不如说你用QQ邮箱,那就写你登录QQ邮箱的帐号 String pass="*******";//登录密码 EmailSender sender=new EmailSender(); Session session= sender.createSession(); MimeMessage message=sender.createMessage(session); System.out.println("正在发送邮件..."); Transport transport=session.getTransport(); transport.connect(server,user,pass); transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO)); transport.close(); System.out.println("发送成功!!!"); } public Session createSession(){ Properties props=new Properties(); props.setProperty("mail.transport.protocol", protocol); props.setProperty("mail.smtp.auth","true"); Session session=Session.getInstance(props); // session.setDebug(true); return session; } public MimeMessage createMessage(Session session)throws Exception{ MimeMessage message=new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); MimeMultipart multipart=new MimeMultipart("related"); MimeBodyPart bodyPart=new MimeBodyPart(); bodyPart.setContent(body,"text/html;charset=gb2312"); multipart.addBodyPart(bodyPart); //发附件 MimeBodyPart gifBodyPart=new MimeBodyPart(); FileDataSource fds=new FileDataSource("f:\\音乐.MP3");//F盘下的 音乐.MP3 文件。这里看个人情况 gifBodyPart.setDataHandler(new DataHandler(fds)); gifBodyPart.setContentID("音乐.MP3"); multipart.addBodyPart(gifBodyPart); message.setContent(multipart); message.saveChanges(); return message; } } //PS:把java发送邮件的导入的JAR包上传了,解压后导入你的项目里就可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值