实现此功能前你需要下载发送邮件所需要的jar包mail.jar,你也可以在此下载。
新建一个Java类文件MyAuthenticator.java,代码如下所示:
- packagecom.ldfsoft.common;
- importjavax.mail.Authenticator;
- importjavax.mail.PasswordAuthentication;
- public classMyAuthenticator extends Authenticator {
- String userName=null;
- String password=null;
- public MyAuthenticator(){
- }
- public MyAuthenticator(String username, String password) {
- this.userName = username;
- this.password = password;
- }
- protected PasswordAuthentication getPasswordAuthentication(){
- return new PasswordAuthentication(userName, password);
- }
- }
此类文件继承了mail.jar包中的Authenticator类。
接着又新建一个dto文件MailSenderDto.java,代码如下所示:
- package com.ldfsoft.dto;
- import java.util.Properties;
- publicclass MailSenderDto {
- // 发送邮件的服务器的IP和端口
- private StringmailServerHost;
- private StringmailServerPort = "25";
- // 邮件发送者的地址
- private StringfromAddress;
- // 邮件接收者的地址
- private StringtoAddress;
- // 登陆邮件发送服务器的用户名和密码
- private StringuserName;
- private Stringpassword;
- // 是否需要身份验证
- privateboolean validate =false;
- // 邮件主题
- private Stringsubject;
- // 邮件的文本内容
- private Stringcontent;
- // 邮件附件的文件名
- private String[]attachFileNames;
- /**
- * 获得邮件会话属性
- */
- public PropertiesgetProperties(){
- Properties p = new Properties();
- p.put("mail.smtp.host",this.mailServerHost);
- p.put("mail.smtp.port",this.mailServerPort);
- p.put("mail.smtp.auth",validate ? "true" :"false");
- return p;
- }
- public String getMailServerHost(){
- returnmailServerHost;
- }
- publicvoid setMailServerHost(String mailServerHost){
- this.mailServerHost = mailServerHost;
- }
- publicStringgetMailServerPort() {
- returnmailServerPort;
- }
- publicvoid setMailServerPort(String mailServerPort){
- this.mailServerPort = mailServerPort;
- }
- publicboolean isValidate() {
- returnvalidate;
- }
- publicvoid setValidate(boolean validate) {
- this.validate = validate;
- }
- public String[] getAttachFileNames(){
- returnattachFileNames;
- }
- publicvoid setAttachFileNames(String[] fileNames){
- this.attachFileNames = fileNames;
- }
- public String getFromAddress() {
- returnfromAddress;
- }
- publicvoid setFromAddress(String fromAddress) {
- this.fromAddress = fromAddress;
- }
- public String getPassword() {
- returnpassword;
- }
- publicvoid setPassword(String password) {
- this.password = password;
- }
- public String getToAddress() {
- returntoAddress;
- }
- publicvoid setToAddress(String toAddress) {
- this.toAddress = toAddress;
- }
- public String getUserName() {
- returnuserName;
- }
- publicvoid setUserName(String userName) {
- this.userName = userName;
- }
- public String getSubject() {
- returnsubject;
- }
- publicvoid setSubject(String subject) {
- this.subject = subject;
- }
- public String getContent() {
- returncontent;
- }
- publicvoid setContent(String textContent) {
- this.content = textContent;
- }
- }
新建一个Java文件MailSender.java,里面写了两个方法,一个方法用于以文本形式发送邮件,一个以html形式发送邮件,代码如下所示:
- package com.ldfsoft.common;
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Address;
- import javax.mail.BodyPart;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- 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;
- import com.ldfsoft.dto.MailSenderDto;
- publicclass MailSender {
- /**
- * 以文本格式发送邮件
- * @param mailInfo待发送的邮件的信息
- */
- publicbooleansendTextMail(MailSenderDto mailInfo) {
- // 判断是否需要身份认证
- MyAuthenticatorauthenticator =null;
- Properties pro =mailInfo.getProperties();
- if(mailInfo.isValidate()) {
- // 如果需要身份认证,则创建一个密码验证器
- authenticator = newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
- }
- // 根据邮件会话属性和密码验证器构造一个发送邮件的session
- SessionsendMailSession = Session.getDefaultInstance(pro,authenticator);
- try {
- // 根据session创建一个邮件消息
- Message mailMessage =new MimeMessage(sendMailSession);
- // 创建邮件发送者地址
- Address from = newInternetAddress(mailInfo.getFromAddress());
- // 设置邮件消息的发送者
- mailMessage.setFrom(from);
- // 创建邮件的接收者地址,并设置到邮件消息中
- Address to = newInternetAddress(mailInfo.getToAddress());
- mailMessage.setRecipient(Message.RecipientType.TO,to);
- // 设置邮件消息的主题
- mailMessage.setSubject(mailInfo.getSubject());
- // 设置邮件消息发送的时间
- mailMessage.setSentDate(new Date());
- // 设置邮件消息的主要内容
- String mailContent =mailInfo.getContent();
- mailMessage.setText(mailContent);
- // 发送邮件
- Transport.send(mailMessage);
- returntrue;
- } catch(MessagingException ex) {
- ex.printStackTrace();
- }
- returnfalse;
- }
- /**
- *以HTML格式发送邮件
- *@param mailInfo待发送的邮件信息
- */
- public boolean sendHtmlMail(MailSenderDto mailInfo){
- // 判断是否需要身份认证
- MyAuthenticatorauthenticator =null;
- Properties pro =mailInfo.getProperties();
- //如果需要身份认证,则创建一个密码验证器
- if(mailInfo.isValidate()) {
- authenticator = newMyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
- }
- // 根据邮件会话属性和密码验证器构造一个发送邮件的session
- SessionsendMailSession = Session.getDefaultInstance(pro,authenticator);
- try {
- // 根据session创建一个邮件消息
- Message mailMessage =new MimeMessage(sendMailSession);
- // 创建邮件发送者地址
- Address from = newInternetAddress(mailInfo.getFromAddress());
- // 设置邮件消息的发送者
- mailMessage.setFrom(from);
- // 创建邮件的接收者地址,并设置到邮件消息中
- Address to = newInternetAddress(mailInfo.getToAddress());
- // Message.RecipientType.TO属性表示接收者的类型为TO
- mailMessage.setRecipient(Message.RecipientType.TO,to);
- // 设置邮件消息的主题
- mailMessage.setSubject(mailInfo.getSubject());
- // 设置邮件消息发送的时间
- mailMessage.setSentDate(new Date());
- // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
- Multipart mainPart = new MimeMultipart();
- // 创建一个包含HTML内容的MimeBodyPart
- BodyPart html = newMimeBodyPart();
- // 设置HTML内容
- html.setContent(mailInfo.getContent(),"text/html; charset=utf-8");
- mainPart.addBodyPart(html);
- // 将MiniMultipart对象设置为邮件内容
- mailMessage.setContent(mainPart);
- // 发送邮件
- Transport.send(mailMessage);
- returntrue;
- } catch(MessagingException ex) {
- ex.printStackTrace();
- }
- returnfalse;
- }
- }
新建一个工具类JavaUtil.java用于封装发送邮件的方法,代码如下所示:
- packagecom.ldfsoft.util;
- import com.ldfsoft.common.MailSender;
- importcom.ldfsoft.dto.MailSenderDto;
- public classJavaUtil {
- /**
- * 发送邮件
- */
- public void sendEmail(String email) {
- try{
- String mailTitle="【我的网盘】账号激活邮件";
- String mailContent="<br><br>亲爱的【我的网盘】用户:<br><br>"+
- " 您好!感谢您注册【我的网盘】帐号,点击下面的链接即可完成注册:<br><br>"+
- " <ahref=\"http://localhost:9080/mydisk/swf/activateEmail.html#email="+email+"\">http://localhost:9080/mydisk/swf/activateEmail.html#email="+email+"</a><br><br>"+
- " (如果链接无法点击,请将它复制并粘贴到浏览器的地址栏中访问)<br><br>"+
- " 您的Email:"+email+"<br><br>"+
- " Email可以作为您的帐号来登录【我的网盘】。<br><br>"+
- " 本邮件是系统自动发送的,请勿直接回复!感谢您的访问,祝您使用愉快!<br><br>"+
- " 【我的网盘】服务中心";
- MailSenderDto mailInfo = newMailSenderDto();
- mailInfo.setMailServerHost("smtp.163.com");
- mailInfo.setMailServerPort("25");
- mailInfo.setValidate(true);
- mailInfo.setUserName("lindf123of@163.com");
- mailInfo.setPassword("******");//您的邮箱密码
- mailInfo.setFromAddress("lindf123of@163.com"); //发件人邮箱地址
- mailInfo.setToAddress(email); //收件人邮箱地址
- mailInfo.setSubject(mailTitle);
- mailInfo.setContent(mailContent);
- //这个类主要来发送邮件
- MailSender ms = new MailSender();
- ms.sendHtmlMail(mailInfo);//发送html格式
- }catch(Exception e){
- System.out.println("失败了!");
- }
- }
- }
其中此方法的参数为要发送的邮件。