javamail的邮件发送功能实现

时间:2021-03-27 19:00:06

本文是基于邮件开发功能–javamail这篇文章,结合自己开发学习中用到的调试的一个邮件发送功能。前面的关于javamail的介绍就参考上文了,直接进入主题。

1、主要用到的包:
javamail的邮件发送功能实现
自己搜索下载。

2、javamail的api:参考

3、导入包后,建立如下文件:
sendMail发送邮件的主类,从xml文件中读取相应信息进行发送。

public class SendMail { 

private static final Log log = LogFactory.getLog(SendMail.class);

//配置文件xml的路径
private static final String XML_PATH ="SendMail.xml";
private static MailInfo mailInfo = new MailInfo();

/**
* <p>Title:readXML</p>
* <p>Description:读取xml文件,把文件内容以字符串形式输出</p>
* @param xmlPath 配置文件的路径
*/


private String readXML(String xmlPath)throws Exception{
log.debug("xmlPath="+xmlPath);

String fileContent = "";
File file = new File(xmlPath);
if(file.isFile() && file.exists()){
try{
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),"UTF-8");
BufferedReader reader = new BufferedReader(read);
String line = null;
try{
while((line = reader.readLine())!=null){
fileContent += line;
}
reader.close();
read.close();
}catch(IOException e){
e.printStackTrace();
}
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch(FileNotFoundException e){
e.printStackTrace();
}
}else{
throw new Exception("文件不存在,请检查");
}

log.debug("xml="+fileContent);
return fileContent;
}

//解析xml文件
private void parseXML(String xml,String type){
type = type.toLowerCase();
try{
Document doc = DocumentHelper.parseText(xml);

String flag = doc.getRootElement().element(type)+"";
if(flag == null || flag.equals("null")){
throw new DocumentException("传入的type值不对,请重新传入");
}
Element hostEle = (Element) doc.selectSingleNode("mail/logmessage/host");
System.out.println(hostEle.getTextTrim());
if(hostEle == null || "".equals(hostEle.getTextTrim())){
throw new DocumentException("邮件服务器域名错误请查看");
}
mailInfo.setHost(hostEle == null?"":hostEle.getTextTrim());

Element fromEle = (Element) doc.selectSingleNode("/mail/"+type+"/from");
if(fromEle == null || "".equals(fromEle.getTextTrim())){
throw new DocumentException("发件人地址不能为空,检查配置文件");
}
mailInfo.setFrom(fromEle == null?"":fromEle.getTextTrim());

Element titleEle = (Element) doc.selectSingleNode("/mail/"+type+"/title");
mailInfo.setTitle(titleEle == null?"":titleEle.getTextTrim());

Element toEle = (Element) doc.selectSingleNode("/mail/"+type+"/to");
if(toEle == null || "".equals(toEle.getTextTrim())){
throw new DocumentException("收件人地址不能为空,请检查配置文件");
}
mailInfo.setTo(toEle == null?"":toEle.getTextTrim());

Element ccEle = (Element) doc.selectSingleNode("/mail/"+type+"/cc");
mailInfo.setCc(ccEle == null?"":ccEle.getTextTrim());

Element nameEle = (Element) doc.selectSingleNode("/mail/"+type+"/username");
if(nameEle == null || "".equals(nameEle.getTextTrim())){
throw new DocumentException("发件人用户名不能为空,请检查配置文件");
}
mailInfo.setUsername(nameEle == null?"":nameEle.getTextTrim());
Element pwdEle = (Element) doc.selectSingleNode("/mail/"+type+"/password");
if(pwdEle == null || "".equals(pwdEle.getTextTrim())){
throw new DocumentException("发件人密码不能为空,请检查配置文件");
}
mailInfo.setPassword(pwdEle == null?"":pwdEle.getTextTrim());
}catch(DocumentException e){
e.printStackTrace();
}
}

//发送邮件的方法:Authenticator类验证
private void sendMailOfValidate(){
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", mailInfo.getHost());
// System.out.println(mailInfo.getHost());
props.put("mail.smtp.auth", "true");

String password = mailInfo.getPassword();
try{
password = Encrypt.DoEncrypt(password);
}catch(NumberFormatException e1){

}
//System.out.println(password);
//传入发件人的用户名和密码,
MyAuthenticator myauth =
new MyAuthenticator(mailInfo.getUsername(), password);

Session session = Session.getDefaultInstance(props, myauth);
session.setDebug(true);
try{
Transport transport = session.getTransport();
// smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailInfo.getHost(), mailInfo.getUsername(), mailInfo.getPassword());
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailInfo.getFrom()));
//对多个收件人进行处理
// if(mailInfo.getTo()!=null && !"".equals(mailInfo.getTo())){
// String to[] = mailInfo.getTo().split(",");
// for(int i = 0;i<to.length;i++){
message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getTo()));
// }
// }
//对多个抄送进行处理
// if(mailInfo.getCc()!=null && !"".equals(mailInfo.getCc())){
// String cc[] = mailInfo.getCc().split(",");
// for(int i = 0;i<cc.length;i++){
// message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
// }
// }
message.setSubject(mailInfo.getTitle());
message.setText(mailInfo.getContent());
// Transport transport = session.getTransport("smtp");
// transport.sendMessage(message, new InternetAddress(mailInfo.getTo()));;
// Transport.send(message);
transport.sendMessage(message, InternetAddress.parse(mailInfo.getTo()));
}catch(AddressException e){
e.printStackTrace();
}catch(MessagingException e){
e.printStackTrace();
}
}
/**
* <p>title:sendmail</p>
* <p>Description:外部程序调用的入口</p>
* @param type 邮件的类型目前有三种,即logmessage、checkmessage、ordermessage
*/

public void senMail(String type,String content)throws Exception{
log.debug("入参type="+type);
log.debug("入参content="+content);
if(type==null || "".equals(type)||content==null||"".equals(content)){
throw new Exception("方法入参参数值错误");
}
String xml = readXML(XML_PATH);
parseXML(xml, type);
mailInfo.setContent(content);
sendMailOfValidate();
}
public static void main(String[] args) throws Exception{
SendMail mail = new SendMail();
String type = "logmessage";
String content = "欢迎使用javamail邮件开发邮件功能";
mail.senMail(type, content);
System.out.println("*****success*****");
}
}

MailInfo类 :定义邮件需要的字段以及对应的get和set方法

public class MailInfo { 

private String host;
private String from;
private String to;
private String cc;
private String username;
private String password;
private String title;
private String content;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}

MyAuthenticator类:用于对邮件授权

public class MyAuthenticator extends Authenticator{ 
private String username;
private String password;
public MyAuthenticator(String user, String password) {
this.username = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
}

SendMail.xml :邮件配置文件

<?xml version="1.0" encoding="UTF-8"?> 
<mail>
<logmessage>
<host>smtp.163.com</host>
<from>******@163.com</from>
<to>********@qq.com</to>
<cc></cc>
<title>JavaMail Test</title>
<username>********@163.com</username>
<password>授权码(不是邮箱密码)</password>
</logmessage>

<checkmessage>
<host></host>
<from></from>
<to></to>
<cc></cc>
<title></title>
<username></username>
<password></password>
</checkmessage>

<ordermessage>
<host></host>
<from></from>
<to></to>
<cc></cc>
<title></title>
<username></username>
<password></password>
</ordermessage>
</mail>

Encrypt类: 主要是用于对密码进行加密和解密

public class Encrypt { 
//对密码进行加密和解密
public static final int pass1 = 10;
public static final int pass2 = 1;
public Encrypt(){}
//对密码进行加密的方法
public static String DoEncrypt(String str){
StringBuffer enStrBuff = new StringBuffer();
for(int i = 0;i < str.length();i++){
int temch = str.charAt(i);
temch ^= 1;
temch ^=0xa;
enStrBuff.append(Integer.toHexString(temch));
}
return enStrBuff.toString().toUpperCase();
}
//对密码进行解密的方法
public static String DoDecrypt(String str){
String deStr = str.toLowerCase();
StringBuffer deStrBuff = new StringBuffer();
for(int i = 0;i < deStr.length();i+=2){
String subStr = deStr.substring(i,i+2);
int temch = Integer.parseInt(subStr,16);
temch ^= 1;
temch ^=0xa;
deStrBuff.append((char)temch);
}
return deStrBuff.toString();
}
}

以上程序全部测试通过,邮件可以正常发送。
需要注意的问题:
1.邮箱需要开启pop,smtp等协议,具体可以百度邮箱怎么开启。
2.开启这些协议后第三方登陆邮箱发送邮件需要授权码登陆,不是密码登陆,具体如何生成授权码可以百度。一般验证失败问题都出现在这。
3.邮件的主题和内容需要好好写,不然会被识别为垃圾邮件发送失败。

特别感谢月月鸟0820博主的分享,特别感谢qnmdcsdn大神给与的调试上的帮助,共同学习一起进步。