您的位置:首页 > 编程语言 > Java开发

Java-发送邮件(附件、图片)---(五)实例

2015-07-20 12:42 701 查看
1:下载加包 javax.mail-1.4.5.jar

2:JAVA邮件发送的大致过程是这样的的:

1、构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。

2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。

3、通过构建的properties文件和javax.mail.Authenticator具体类来创建一个javax.mail.Session。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。

4、构建邮件内容,一般是javax.mail.internet.MimeMessage对象,并指定发送人,收信人,主题,内容等等。

5、使用javax.mail.Transport工具类发送邮件。

代码如下:

1:首先是继承自javax.mail.Authenticator的一个具体类。getPasswordAuthentication()方法也就是构建一个PasswordAuthentication对象并返回。

MySendMailAuthenticator .java

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

class MySendMailAuthenticator extends Authenticator
{
String username = "";
String password = "";

public MySendMailAuthenticator(String user, String pass) { this.username = user;
this.password = pass; }

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.username, this.password);
}
}


2:邮件发送类,剩下的步骤都是在这个类实现的。

SendMail .java

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
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;

/**
*
* @author javalzbin
*
*/
public class SendMail {

private String smtp = ""; // 邮件服务器主机名
private String protocol = ""; // 邮件传输协议
private String username = ""; // 登录用户名
private String password = ""; // 登录密码
private String from = ""; // 发件人地址
private String to = ""; // 收件人地址
private String cc = "";
private String subject = ""; // 邮件主题
private String body = ""; // 邮件内容
private String port = "587"; // 邮件内容

// 一个有规则的map,用作嵌入图片
Map<String, String> map;
// 存放附件
List<String> list;

public SendMail(Map<String, String> map, List<String> filelist,
Map<String, String> image) {
this.smtp = map.get("smtp");
this.protocol = map.get("protocol");
this.username = map.get("username");
this.password = map.get("password");
this.from = map.get("from");
this.to = map.get("to");
this.cc = map.get("cc");
this.subject = map.get("subject");
this.body = map.get("body");
this.port = map.get("port");

this.list = filelist;
this.map = image;
}

public void send() throws Exception {
Properties pros = new Properties();
pros.setProperty("mail.transport.protocol", this.protocol);
pros.setProperty("mail.host", this.smtp);
//      pros.put("mail.smtp.auth", "true");
//      pros.put("mail.smtp.port", this.port);
MySendMailAuthenticator ma = new MySendMailAuthenticator(this.username, this.password);
Session session = Session.getInstance(pros, ma);
session.setDebug(false);

MimeMessage msg = createMessage(session);

Transport ts = session.getTransport();
ts.connect();
ts.sendMessage(msg, msg.getAllRecipients());

ts.close();
}

public MimeMessage createMessage(Session session) throws Exception {

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(this.from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
message.setSubject(this.subject);

MimeMultipart allMultipart = new MimeMultipart();

// 创建代表邮件正文和附件的各个MimeBodyPart对象
MimeBodyPart contentpart = createContent(this.body);
allMultipart.addBodyPart(contentpart);

// 创建用于组合邮件正文和附件的MimeMultipart对象
for (int i = 0; i < list.size(); i++) {
allMultipart.addBodyPart(createAttachment(list.get(i)));
}

// 设置整个邮件内容为最终组合出的MimeMultipart对象
message.setContent(allMultipart);
message.saveChanges();
return message;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public MimeBodyPart createContent(String body) throws Exception {
// 创建代表组合Mime消息的MimeMultipart对象,将该MimeMultipart对象保存到MimeBodyPart对象
MimeBodyPart contentPart = new MimeBodyPart();
MimeMultipart contentMultipart = new MimeMultipart("related");

// 创建用于保存HTML正文的MimeBodyPart对象,并将它保存到MimeMultipart中
MimeBodyPart htmlbodypart = new MimeBodyPart();
htmlbodypart.setContent(this.body, "text/html;charset=UTF-8");
contentMultipart.addBodyPart(htmlbodypart);

if (map != null && map.size() > 0) {
Set<Entry<String, String>> set = map.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Entry<String, String> entry = (Entry<String, String>) iterator
.next();

// 创建用于保存图片的MimeBodyPart对象,并将它保存到MimeMultipart中
MimeBodyPart gifBodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(entry.getValue());// 图片所在的目录的绝对路径

gifBodyPart.setDataHandler(new DataHandler(fds));
gifBodyPart.setContentID(entry.getKey()); // cid的值
contentMultipart.addBodyPart(gifBodyPart);
}
}

// 将MimeMultipart对象保存到MimeBodyPart对象
contentPart.setContent(contentMultipart);
return contentPart;
}

public MimeBodyPart createAttachment(String filename) throws Exception {
// 创建保存附件的MimeBodyPart对象,并加入附件内容和相应的信息
MimeBodyPart attachPart = new MimeBodyPart();
FileDataSource fsd = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(fsd));
attachPart.setFileName(new String(fsd.getName().getBytes("utf-8"), "ISO8859-1"));
return attachPart;
}

}


3:测试 tomail2 .java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class tomail2 {
public static String fileCheck(String fileName) {
File file = new File(fileName);
String tag = "0";
if (file.exists()) {
tag = "1";
}
return tag;
}
public static String readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
String content = "";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;

while ((tempString = reader.readLine()) != null) {
content = content + tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();

if (reader != null)
try {
reader.close();
} catch (IOException localIOException1) {
}
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException localIOException2) {
}
}
return content;
}

public static void main(String[] argv) throws Exception {
if (argv.length < 4) {
System.out
.println("Usage: java -jar jarfile to cc title content attachment");
System.exit(0);
}
String to = argv[0];
String cc = argv[1];
String title = argv[2];
String content = argv[3];

Map map = new HashMap();
map.put("smtp", "10.127.133.50");
map.put("protocol", "smtp");
```
//      map.put("username", "CTU_PRD");
//      map.put("port", "587");
//      map.put("password", "YESjiayou.123");
map.put("from", "CTU_SUP@cyou-inc.com");

map.put("to", to);

map.put("cc", cc);

map.put("subject", title);

Map image = new HashMap();

List list = new ArrayList();

if (argv.length > 4) {
String attachment = argv[4];
if ((attachment != null) && (!"".equals(attachment))) {
String[] filePaths = (String[]) null;
if (attachment.contains(","))
filePaths = attachment.split(",");
else if (attachment.contains(";"))

a593
filePaths = attachment.split(";");
else {
filePaths = attachment.split(",");
}
if (filePaths != null) {
list.addAll(Arrays.asList(filePaths));
}
}

}

map.put("body", content);

SendMail sm = new SendMail(map, list, image);

sm.send();
}

}


<收件人 抄送 标题 内容 附件地址>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  发送邮件