首页 > 代码库 > java关于发送邮件的一些常见问题分享

java关于发送邮件的一些常见问题分享

  温馨提示:由于发送邮件次数过多,会被官方标注,以至于邮件会放到垃圾邮箱,测试的小伙伴们注意了!

废话不多说,下面上代码:



package com.tpyin.test;

import java.util.Properties;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.HtmlEmail;

/**

 * 

 * @author 执草书云

 *发送邮箱测试

 *所需jar包

 *mail.jar

 *commons-email-1.1.jar

 *

 *注意事项:

 *使用myeclipse开发在导入jar包时有可能会和Java EE 5 Libraries 的mail包冲突而抛出异常

 *Exception in thread "main" java.lang.NoClassDefFoundError: com/mail/util/LineInputStream

at javax.mail.internet.MimeUtility.<clinit>(MimeUtility.java:1161)

at javax.mail.internet.InternetAddress.setPersonal(InternetAddress.java:216)

at org.apache.commons.mail.Email.createInternetAddress(Email.java:525)

at org.apache.commons.mail.Email.setFrom(Email.java:600)

at org.apache.commons.mail.Email.setFrom(Email.java:583)

at com.beauty.common.Sendemail.sendMail(Sendemail.java:22)

at com.beauty.common.Sendemail.main(Sendemail.java:45)

 *

 *解决方法:本人用的myelipse10 下面就已10为例

 *打开myeclipse安装目录

 *E:\myeclipse10\Common\plugins\com.genuitec.eclipse.j2eedt.core_10.0.0.me201203160414\data\libraryset\EE_5,以压缩包形式打开javaee.jar,然后删除mail即可

 **/

public class Sendemail {

public static boolean sendMail(String mailTo, String subject,

String mailContext) {

try {

HtmlEmail email = new HtmlEmail();// 实例化对

email.setHostName("smtp.163.com");// 设置发件人的服务器

email.setFrom("jiayonghui1994@163.com", "美客中国");

email.setAuthentication("jiayonghui1994@163.com", "954475052");// 参数注释:发件人邮箱(账号,密码)

email.addTo(mailTo, "客户");//设置发送地址

email.setCharset("gbk");//解决发送内容乱码

email.setSubject(subject);//发送标题

email.setHtmlMsg(mailContext);// 邮件发送的内容

Properties props = System.getProperties();

// // 设置邮件服务器

props.put("mail.smtp.host", "smtp.163.com");

props.put("mail.smtp.auth", "true");

email.send();//发送

return true;

} catch (EmailException e) {

e.printStackTrace();

return false;

}

}

public static void main(String[] args) {

String code="收到没,perfect";

String mailTo = "//设定要发送的邮箱";

String subject = "认证邮箱,任你畅享美时美刻";

String mailContext = "您正在验证邮箱,验证码是:" + code;

boolean m= sendMail(mailTo, subject, mailContext);

System.out.println(m);

}

}

本文出自 “12241542” 博客,请务必保留此出处http://12251542.blog.51cto.com/12241542/1876580

java关于发送邮件的一些常见问题分享