JavaMail开发笔记

开发前要先下载mail.jar,如果用Myeclipse开发会有冲突,因myeclipse中自带有mail.jar,但不好用,解决办法:删除相关 mail类,如我的删除方法是找到myeclipse安装目录
D:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset \EE_5\javaee.jar,
用7-zip压缩软件打开,删除下面的mail文件夹


像java.net类那样,JavaMail API通过使用授权者类(Authenticator)以用户名、密码的方式访问那些受到保护的资源,在这里“资源”就是指邮件服务器。
在 javax.mail包中可以找到这个JavaMail的授权者类(Authenticator)。在使用Authenticator这个抽象类时,我们必须采用继承该抽象类的方式,
并且该继承类必须具有返回PasswordAuthentication对象(用于存储认证时要用到的用户名、密码)getPasswordAuthentication()方法。并且要在Session中进行注册,
使Session能够了解在认证时该使用哪个类。

账号密码的封装类
package com.tg.email;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {
public static String MAIL_USER = "[email protected]";

public static String MAIL_PASSWORD = "888888";

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MAIL_USER, MAIL_PASSWORD);
}
}

邮件发送类
package com.tg.email;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
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 org.springframework.stereotype.Component;


public class SendMail{
private String mailTo = null; // 邮件接收者
private String mailReply = null; // 邮件回复地址
private String smtpHost = null; // SMTP服务器
private boolean debug = false;
private String subject; // 邮件主题
private String msgContent; // 邮件内容
private String messageContentMimeType = "text/html;charset=utf-8"; // 邮件内容格式

/**
* 填充邮件相关信息Method
*
*
@param session
*
@param msg
*
@throws IOException
*
@throws MessagingException
*/
private void fillMail(MimeMessage msg) throws IOException, MessagingException {

if (mailReply != null) {
msg.setFrom(new InternetAddress(mailReply));
System.out.println("发送人Mail地址:" + mailReply);
} else {
System.out.println("没有指定发送人邮件地址!");
return;
}
if (mailTo != null) {
msg.setRecipients(Message.RecipientType.TO, mailTo);
System.out.println("接收人Mail地址:" + mailTo);
} else {
System.out.println("没有指定收件人邮件地址!");
return;
}
msg.setSubject(subject);
InternetAddress[] replyAddress = { new InternetAddress(mailReply) };
msg.setReplyTo(replyAddress);

MimeBodyPart mBodyContent = new MimeBodyPart(); // 设置内容编码和内容
if (msgContent != null) {
mBodyContent.setContent(msgContent, messageContentMimeType);
} else {
mBodyContent.setContent("", messageContentMimeType);
}
Multipart mPart = new MimeMultipart(); // 模拟信息所需邮件内容方法的参数
mPart.addBodyPart(mBodyContent);
msg.setContent(mPart);
msg.setSentDate(new Date());
}

@SuppressWarnings("static-access")
public int sendMail() throws IOException, MessagingException {
Properties props = System.getProperties(); // JavaMail需要Properties来创建一个session对象,其属性值就是发送邮件的主机
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.auth", "true");

Authenticator auth = new MailAuthenticator();
Session session = Session.getInstance(props, auth); // 创建session对象
// 启动JavaMail调试功能,可以返回与SMTP服务器交互的命令信息
// 可以从控制台中看一下服务器的响应信息
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session); // 创建模拟邮件信息
Transport trans = null; // 创建发送对象
fillMail(msg);

try {
trans = session.getTransport("smtp");
try {

trans.connect(smtpHost, MailAuthenticator.MAIL_USER, MailAuthenticator.MAIL_PASSWORD);
System.out.println("smtp服务器连接成功.....");
} catch (AuthenticationFailedException e) {
System.out.println("发送邮件失败:错误代码"+e.getMessage());
return 3;
} catch (MessagingException e) {
System.out.println("发送邮件失败:错误代码"+e.getMessage());
return 3;
}
System.out.println("邮件发送中.....");
trans.send(msg); // 发送邮件
System.out.println("邮件发送成功!");
trans.close();
} catch (MessagingException e) {
System.out.println("发送邮件失败:错误代码"+e.getMessage());
} finally {
try {
if (trans != null && trans.isConnected()) {
trans.close();
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
return 0;
}

public int sendMail(String smtpHost, String replyAddress, String mailTo, String subject, String content) throws IOException, MessagingException {
this.smtpHost = smtpHost == null ? "smtp.163.com" : smtpHost;
this.mailReply = replyAddress == null ? MailAuthenticator.MAIL_USER : replyAddress;
this.mailTo = mailTo;
this.subject = subject;
this.msgContent = content;
return sendMail();
}
public SendMail() {
}
}

/**
* main方法测试
*
@param args
*/
public static void main(String[] args) {
SendMail sm=new SendMail();
sm.setSmtpHost("smtp.163.com");
sm.setMailReply("[email protected]");
sm.setMailTo("[email protected]");
sm.setMsgContent("测试邮件,请注意查收,如有问题,请联系开发人员!");
sm.setSubject("邮件标题");
try {
sm.sendMail();
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
setter和getter可根据需求生成



你可能感兴趣的:(javamail)