之前没做过用JavaMail来发送邮件,在网上搜索点资料,自己写了2方法测试了下:
在自己的项目中,引入三个包 mail.jar ,commons-email-X.X.jar ,activation.jar。下载地址http://u.115.com/file/bhaewa0d
下面是我的代码类:
public class EmailMain {
/**
* 方法测试一个简单拼凑的html
*/
public static void send() {
try {
HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.163.com");// 发送方smtp
email.setAuthentication("username", "password");//发送方的邮箱用户名,密码
email.addTo("address", "username");//接受方的邮箱地址,邮箱用户名
email.setFrom("address@163.com", "username");//发送方的邮箱地址,邮箱用户名
email.setSubject("主题:该邮件包括html格式内容");
email.setCharset("UTF-8");// 编码格式
// 注意这里:embed 将帮助我们创建标签如:cid:xxx url
URL url = new URL("https://i-blog.csdnimg.cn/blog_migrate/658eede2c8111f79c58de644643672a3.png");
String cid = email.embed(url, "Apache logo");
/**
* 我们看到HtmlEmail extends
* Email的,它依然有setMsg(),但是这里发送的邮件包括了插入在邮件内容中的图片,
* 所以不能在使用了setMsg(),而要以setHtmlMsg 或setTextMsg代码
**/
email.setHtmlMsg("发送第一封邮件,The apache logo -
+ cid + "\">");
// set the alternative message
.setTextMsg("Your email client does not support HTML messages");
// set mail
email.send();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 测试读取本地html页面,发送邮件(页面内容过多,最好用此方法)
*/
public static void sendFileContext() {
try {
HtmlEmail email = new HtmlEmail();
email.setHostName("smtp.163.com");// 发送方smtp
email.setAuthentication("username", "password");//发送方的邮箱用户名,密码
email.addTo("address", "username");//接受方的邮箱地址,邮箱用户名
email.setFrom("address@163.com", "username");//发送方的邮箱地址,邮箱用户名
email.setSubject("主题:该邮件包括html格式内容");
File file = new File(
"D:\\Documents and Settings\\wanghuijiao\\textSendEmail.jsp");
BufferedReader reader = null;
StringBuilder msg = new StringBuilder("");
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
msg.append(tempString);
}
} catch (Exception e) {
}
String message = msg.toString();
message = new String(message.getBytes("utf-8"), "ISO-8859-1");// 处理中文乱码转码
email.setHtmlMsg(message);
email.send();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] arg) {
sendFileContext();
}
textSendEmail.jsp內容如下:
}