java实现邮件的发送包括网页文件的发送

本文出自 “ java开发笔记” 博客 出处 http://gaoqifang.blog.51cto.com/2270113/758306
说明:1、本程序可实现网页文件、普通文件的发送。
2、实现邮件发送需要三个jar包的支持: commons-codec-1.3.jarcommons-httpclient-3.0.jar(这两个jar包实现抓取互联网网页内容)以及mail.jar
具体实现:
一、首先建立MailAuthenticator类,继承自javax.mail.Authenticator类。此类实现发件箱的登陆验证。
package com.company.simplemail;

import javax.mail.Authenticator;

import javax.mail.PasswordAuthentication;

/**
* 服务器邮箱登录验证
*/

public class MailAuthenticator extends Authenticator {

// 用户名(登录邮箱)
private String username;

// 密码
private String password;

/**
* 初始化邮箱和密码
* @param username 邮箱
* @param password 密码
*/

public MailAuthenticator(String username, String password){
this.username = username;
this.password = password;
}

String getPassword() {
return password;
}

@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}

String getUsername() {
return username;
}

public void setPassword(String password) {
this.password = password;
}

public void setUsername(String username) {
this.username = username;
}

}
二、 建立SimpleMailSender类,此类实现邮件的单发、群发等等,是邮件发送的核心类
package com.company.simplemail;

import java.util.List;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;


/**
* 简单邮件发送器,可单发,群发。
*/

public class SimpleMailSender {
// 发送邮件的props文件
private final transient Properties props = System.getProperties();

// 邮件服务器登录验证
private transient MailAuthenticator authenticator;

// 邮箱session
private transient Session session;

/**
* 初始化邮件发送器
* @param smtpHostName SMTP邮件服务器地址
* @param username 发送邮件的用户名(地址)
* @param password 发送邮件的密码
*/

public SimpleMailSender( final String smtpHostName, final String username,
final String password) {
init(username, password, smtpHostName);
}

/**
* 初始化邮件发送器
* @param username 发送邮件的用户名(地址),并以此解析SMTP服务器地址
* @param password 发送邮件的密码
*/

public SimpleMailSender( final String username, final String password) {
// 通过邮箱地址解析出smtp服务器,对大多数邮箱都管用
final String smtpHostName = "smtp." + username.split( "@")[1];
init(username, password, smtpHostName);
}

/**
* 初始化
* @param username 发送邮件的用户名(地址)
* @param password 密码
* @param smtpHostName SMTP主机地址
*/

private void init(String username, String password, String smtpHostName) {
// 初始化props
props.put( "mail.smtp.auth", "true");
props.put( "mail.smtp.host", smtpHostName);
// 验证
authenticator = new MailAuthenticator(username, password);
// 创建session
session = Session.getInstance(props, authenticator);
}

/**
* 发送邮件
* @param recipient收件人邮箱地址
* @param subject邮件主题
* @param content邮件内容
* @throws AddressException
* @throws MessagingException
*/

public void send(String recipient, String subject, String content)
throws AddressException, MessagingException {
// 创建mime类型邮件
final MimeMessage message = new MimeMessage(session);
// 设置发信人
message.setFrom( new InternetAddress(authenticator.getUsername()));
// 设置收件人
message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
// 设置主题
message.setSubject(subject);
// 设置邮件内容
Multipart mp = new MimeMultipart( "related");
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(content.toString(), "text/html;charset=utf-8");
mp.addBodyPart(mbp);
message.setContent(mp);


// 设置邮件内容
// message.setContent(content.toString(), "text/html;charset=utf-8");
// 发送
Transport.send(message);
}

/**
* 群发邮件
* @param recipients收件人们
* @param subject 主题
* @param content 内容
* @throws AddressException
* @throws MessagingException
*/

public void send(List<String> recipients, String subject, String content)
throws AddressException, MessagingException {
// 创建mime类型邮件
final MimeMessage message = new MimeMessage(session);
// 设置发信人
message.setFrom( new InternetAddress(authenticator.getUsername()));
// 设置收件人们
final int num = recipients.size();
InternetAddress[] addresses = new InternetAddress[num];
for ( int i = 0; i < num; i++) {
addresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(RecipientType.TO, addresses);
// 设置主题
message.setSubject(subject);
// 设置邮件内容
message.setContent(content.toString(), "text/html;charset=utf-8");
// 发送
Transport.send(message);
}

/**
* 发送邮件
* @param recipient收件人邮箱地址
* @param mail邮件对象
* @throws AddressException
* @throws MessagingException
*  
*/

public void send(String recipient, SimpleMail mail)
throws AddressException, MessagingException {
send(recipient, mail.getSubject(), mail.getContent());
}

/**
* 群发邮件
* @param recipients 收件人们
* @param mail 邮件对 象 
* @throws AddressException
* @throws MessagingException
*/

public void send(List<String> recipients, SimpleMail mail)
throws AddressException, MessagingException {
send(recipients, mail.getSubject(), mail.getContent());
}
}
三、 建立 SimpleMail,这只是个普通邮件类,主要用来封装所要发送的邮件信息。
package com.company.simplemail;

public class SimpleMail {
//邮件中的主题
private String subject;
//邮件的内容(正文)
private String content;
//可根据需要增加其他邮件元素

public void setSubject(String subject) {
this.subject = subject;
}

public void setContent(String content) {
this.content = content;
}

public String getSubject() {
return subject;
}

public String getContent() {
return content;
}
}
四、 建立ReadHtmlFile类,此类用来读取网页文件(当然也能读取普通文件),将文件转换成String用来发送

 

package com.company.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;

public class ReadHtmlFile {

public static HttpClient client = new HttpClient();

//读取普通文件
public static String readFile(String filename) {
File file = new File(filename);
Reader reader = null;
StringBuffer stb = new StringBuffer();
int charread = 0;
char[] temps = new char[100];
try {
reader = new InputStreamReader( new FileInputStream(file));
while ((charread = reader.read(temps)) != -1) {
if (charread == temps.length) {
stb.append(temps);
temps = new char[100];
charread = 0;
}
}
stb.append(temps);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
String str = stb.toString();
return str;
}

/**
*
* 所要发送的网页中,不要使用外联样式,脚本等,
* 因为各大邮箱后台的过滤算法会过滤掉css,script等
* 样式用标签style属性写
* 图片、链接必须使用绝对地址 (http://.....) 形式才能接收显示
* */

public static String getSource(String url) {

GetMethod method = new GetMethod(url);

try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
InputStream in = null;
try {
in = method.getResponseBodyAsStream();
} catch (IOException e1) {

// e1.printStackTrace();
}
in = new BufferedInputStream(in);
Reader r = new InputStreamReader(in);
int c;
StringBuffer buffer = new StringBuffer();

try {
while ((c = r.read()) != -1)
buffer.append(( char) c);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
method.releaseConnection();

return buffer.toString();
}
}
五、建立测试类,可以发送邮件了!!!
package com.company.simplemail;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.company.util.ReadHtmlFile;

public class MailTest {
/**
* 单发
* */

@Test
public void testSingleSend(){
SimpleMail sm= new SimpleMail();
sm.setSubject( "第一封邮件");
String str = ReadHtmlFile.getSource( "http://www.baidu.com");
//String str = ReadHtmlFile.readFile("这里填写你需要发送的本地文件路径");
System.out.println(str);
sm.setContent(str);
SimpleMailSender sms=new SimpleMailSender(""这里填写你的发件箱","这里填写你的发件箱密码");
try {
sms.send("这里需要填写接收邮件的邮箱", sm);
System.out.println("执行完成!!");
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 群发
*
* */

@Test
public void testMassSend(){
SimpleMail sm=new SimpleMail();
sm.setSubject("第一封邮件");
String str = ReadHtmlFile.getSource("http://www.baidu.com");
//String str = ReadHtmlFile.readFile("这里填写需要发送的本地文件路径");
System.out.println(str);
sm.setContent(str);
SimpleMailSender sms=new SimpleMailSender("这里填写你的发件箱","这里填写你的发件箱密码");
List<String> recipients=new ArrayList<String>();
recipients.add("这里需要填写接收邮件的邮箱");
recipients.add("这里需要填写接收邮件的邮箱");
recipients.add("这里需要填写接收邮件的邮箱");
recipients.add("这里需要填写接收邮件的邮箱");
try {
sms.send(recipients, sm);
System.out.println("执行完成!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后再次强调:1,所要发送的网页中,不要使用外联样式,脚本等,因为各大邮箱后台的过滤算法会过滤掉css,script等。
2,样式用标签style属性写
3, 图片、链接必须使用绝对地址 (http://.....) 形式才能接收显示
4,一般用于发送的网页文件都是按上面说的要求,自己另外制作的,专门用于邮件发送的网页。在互联网上抓取的网页发送后,一般都不能在收件箱中完美的显示

 

 

你可能感兴趣的:(java,java程序员,java知识)