javaMail邮件发送
利用Sun公司提供的JavaMail API可以很方便的开发邮件发送程序。也许你已经可以利用它来发送一段简单的文本了,但想不想使你的程序像OUTLOOK一样也能发送附件呢?本文在简单介绍了JavaMail之后,详细讲解了一段完整的送信的JavaBean及一个十分轻巧的servlet。
(没有装载JavaMail API的读者,可以到此站点下载,并按照Readme.txt设置好ClassPath)
一、JavaMail中一些我们需要的类
1.Properties
JavaMail需要Properties来创建一个session对象,其属性值就是发送邮件的主机,如:
Properties props = new Properties (); props.put("mail.smtp.host", "smtp.xxxx.com");//可以换上你的smtp主机名,就像你在OutLook中设置smtp主机名一样。 |
2.Session
所有的基于JavaMail的程序都至少需要一个或全部的对话目标。
Session session = Session.getInstance(props, null); |
3.MimeMessage
信息对象将把你所发送的邮件真实的反映出来。
MimeMessage msg = new MimeMessage(session); |
4.Transport
邮件的发送是由Transport来完成的:
Transport.send(msg); |
二、我们自己创建的可发送附件的类
import java.util.* ; import java.io.* ; import javax.mail.* ; import javax.mail.internet.* ; import javax.activation.* ; public class Mail { //定义发件人、收件人、主题等 String to=""; String from=""; String host=""; String filename=""; String subject=""; //用于保存发送附件的文件名的集合 Vector file = new Vector(); //做一个可以传发件人等参数的构造 public Mail (String to,String from,String smtpServer,String subject){ //初始化发件人、收件人、主题等 this.to=to; this.from=from; this.host=smtpServer; this.subject=subject; } //该方法用于收集附件名 public void attachfile(String fname){ file.addElement(fname); } //开始发送信件的方法 public boolean startSend(){ //创建Properties对象 Properties props = System.getProperties(); //创建信件服务器 props.put("mail.smtp.host", host); //得到默认的对话对象 Session session=Session.getDefaultInstance(props, null); try { //创建一个消息,并初始化该消息的各项元素 MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address={new InternetAddress(to)}; msg.setRecipients(Message.RecipientType.TO,address); msg.setSubject(subject); //后面的BodyPart将加入到此处创建的Multipart中 Multipart mp = new MimeMultipart(); //利用枚举器方便的遍历集合 Enumeration efile=file.elements(); //检查序列中是否还有更多的对象 while(efile.hasMoreElements()){ MimeBodyPart mbp=new MimeBodyPart(); //选择出每一个附件名 filename=efile .nextElement().toString(); //得到数据源 FileDataSource fds=new FileDataSource(filename); //得到附件本身并至入BodyPart mbp.setDataHandler(new DataHandler(fds)); //得到文件名同样至入BodyPart mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } //移走集合中的所有元素 file.removeAllElements(); //Multipart加入到信件 msg.setContent(mp); //设置信件头的发送日期 msg.setSentDate(new Date()); //发送信件 Transport.send(msg); } catch (MessagingException mex) { mex.printStackTrace(); Exception ex = null; if ((ex=mex.getNextException())!=null){ ex.printStackTrace(); } return false; } return true; } } |
下面是一个源码
package com;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Message;
import org.springframework.stereotype.Component;
import com.util.SysGlobal;
@Component("sendmail")
public class SendMail {
private static File file;
public static void main(String[] args) throws IOException{
SendMail sendmail=new SendMail();
String sendEmail = "chenlichenli520@126.com";
String sendPwd = "******";
String host = "smtp.126.com";
FileReader reader=new FileReader("chen.txt");//此处是一个文件名,发送邮件的信息全部放在此txt文件中
BufferedReader buf=new BufferedReader(reader);
String context="";
String row="";
while((row=buf.readLine())!=null)
{
context=context+row+"\n<br/>";
}
context =SendMail.removeFFFE(context);
context=context.replaceAll("\\&\\{email\\}","jimmychenli@126.com");
context=context.replaceAll("\\&\\{info\\}","ss");
System.out.println(context);
String info=context;
if(sendmail.send(sendEmail, "393758826@qq.com",sendPwd,host,info)){
System.out.println("邮件发送成功");
}
}
private static String removeFFFE(String s) {
for(int i=0; i<2; i++) {
if(s.length()>1) {
char c = s.charAt(0);
if(c==0xfffe || c==0xfeff)
s = s.substring(1);
}
}
return s;
}
public static boolean send(String from,String to,String password,String host,String info){
Properties props=new Properties();
// 与服务器建立Session的参数设置
props.put("mail.smtp.host", host);// host服务器。
props.put("mail.smtp.auth", "true");//服务自动验证
Session mailSession=Session.getDefaultInstance(props,null);//与服务器建立连接
try{
//Transport用来发送邮件传输协议
Transport trans=mailSession.getTransport("smtp");
trans.connect(host,from,password);
//创建邮件发送信息
Message newMessage=new MimeMessage(mailSession);
newMessage.setSubject("温馨提示");//设计发送邮件的主题
newMessage.setFrom(new InternetAddress(from));//设定所发人的邮箱;
BodyPart fileBodyPart=new MimeBodyPart();
/* FileDataSource fds=new FileDataSource(file);
fileBodyPart.setDataHandler(new DataHandler(fds));*/
fileBodyPart.setHeader("text/html", "utf-8");
Address addressTo[] = { new InternetAddress(to)};
newMessage.setRecipients(Message.RecipientType.TO, addressTo);
fileBodyPart.setContent(info,"text/html;charset=utf-8");//设定可以发送HTML格式的邮件,最终将显示HTML
MimeMultipart multi = new MimeMultipart();
multi.addBodyPart(fileBodyPart);
newMessage.setContent(multi);
newMessage.saveChanges();
trans.sendMessage(newMessage, newMessage.getRecipients(Message.RecipientType.TO));
trans.close();
return true;
}catch(Exception ex){
ex.printStackTrace();
return false;
}
}
}