Java实现邮件发送

来源:互联网 发布:编程珠玑 英文版 pdf 编辑:程序博客网 时间:2024/06/06 02:59

在项目开发中,很多地方需要用到邮件发送的功能,例如:注册用户是邮箱验证。那么,接下来将通过一个案例实现发送邮件的功能!

1、创建工程,导入mail.jar。该jar包提供邮件发送的核心类及其方法


2、创建类SendMail.java,并创建邮箱服务器连接

package edu.zzuli.demo.entity;import java.util.Properties;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;/** *  * @author zjc * @date  2015-9-5 * @time 下午05:01:10 * @20150905_mail * @  */public class SendMail {public static void main(String[] args) {sendEmail();}public static void sendEmail(){String str="<html>请激<a href=''>活邮箱</a>..<h1>测试</h1>!</html>";//1.创建邮箱服务器链接Properties properties=new Properties();properties.put("mail.transport.protocol", "smtp");//发送协议properties.put("mail.smtp.auth", "true");//是否需要验证Session session=Session.getInstance(properties);session.setDebug(true);//开启调试}}
3、邮件信息配置
//2.邮件信息配置Message message=new MimeMessage(session);try {//设置发件人邮箱message.setFrom(new InternetAddress("xxxx@qq.com"));MimeMultipart mp=new MimeMultipart();//创建HTML载体 <html></html>//正文BodyPart part=new MimeBodyPart();//设置主体<body></body>part.setContent(str, "text/html;charset=utf-8");mp.addBodyPart(part);message.setContent(mp);message.setSubject("您中了500万,请立即领取--");//设置标题} catch (AddressException e) {e.printStackTrace();} catch (MessagingException e) {e.printStackTrace();}

4、发送消息配置

//3.发送消息配置Transport tran=session.getTransport();//链接邮箱服务器tran.connect("smtp.qq.com", 25, "xxxx@qq.com", "");tran.sendMessage(message, new Address[]{new InternetAddress("xxxx@qq.com"),new InternetAddress("xxxx@qq.com"),new InternetAddress("xxxx@qq.com")});tran.close();

1 0
原创粉丝点击