以下内容介绍JAVA如何发送各种邮件,以及发送失败邮件重试发送。
一.需要的类库
1.javamail
2.ical4j-1.0.1.jar
3.commons-logging-1.1.1.jar
4.commons-lang-2.6.jar
5.backport-util-concurrent-3.1.jar
其中2、3、4、5在发送会议邀请类邮件时才会用到
二.javamail的初始化操作
private String from = "aa@sina.com";
private String to = "ss@sina.com";//收件人
private String subject = "";//标题
private String content = "ssss";//邮件内容
//链接邮件服务器
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.highteam.com");
props.put("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "yin.zhang@highteam.com"; //大多数是你邮件@前面的部分
String pwd = "binglan212";
return new PasswordAuthentication(username, pwd);
}
};
Session mailSession = Session.getInstance(props, auth);
//获取Message对象
Message msg = new MimeMessage(mailSession);
try {
//设置邮件基本信息
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSentDate(new java.util.Date());
msg.setSubject(subject);
//msg.setContent(content, "text/html;charset=UTF-8");//这是做简单的设置邮件内容的方式
Multipart mp = getContent();//获取不同类型的邮件的邮件内容
msg.setContent(mp);
msg.saveChanges();
} catch (Exception ex) {
Logger.getLogger(Email.class.getName()).log(Level.SEVERE, null, ex);
}
//发送邮件
try {
Transport.send(msg);
return true;
} catch (SendFailedException e) {//邮件地址无效
System.out.println(e);
return false;
} catch (Exception e) {
//重新发送,若邮件地址无效则会造成无限循环
Timer timer = new Timer();
timer.schedule(new Mail(msg, timer), 10000);
System.out.println(e);
return false;
}
//Mail类,用于重发邮件的类
private class Mail extends TimerTask {
private Timer timer = null;
private Message msg = null;
public Mail(Message msg, Timer timer) {
this.msg = msg;
this.timer = timer;
}
@Override
public void run() {
if (!send()) {//发送失败,重发
timer.schedule(new Mail(msg, timer), 10000);
} else {
timer.cancel();
}
}
private boolean send() {
try {
Transport.send(msg);
return true;
} catch (Exception e) {
System.out.println(e);
return false;
}
}
}
三.各种类型邮件
1. 普通邮件,只包含文本内容
private Multipart getContent() throws Exception {
//设置邮件内容
MimeMultipart mm = new MimeMultipart();
BodyPart mbp = new MimeBodyPart();
mbp.setContent(content, "text/html;charset=UTF-8");
mm.addBodyPart(mbp);
return mm;
}
2.包含附件
private Multipart getContent() throws Exception {
//设置邮件内容
MimeMultipart mm = new MimeMultipart();
BodyPart mbp = new MimeBodyPart();
mbp.setContent(content, "text/html;charset=UTF-8");
mm.setSubType("related");
mm.addBodyPart(mbp);
//将需上传的文件转换为二进制
String attachment = "E:/aaa.txt";
File file = new File(attachment);
if (!file.exists()) {
return mm;
}
BufferedInputStream in = new BufferedInputStream(new FileInputStream(attachment));
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
byte[] attach_bytes = out.toByteArray();
in.close();
out.close();
//转换文件为二进制操作结束
if (attach_bytes != null && attach_bytes.length > 0) {
mbp = new MimeBodyPart();
DataHandler dh = new DataHandler(new ByteArrayDataSource(attach_bytes, "application/octet-stream"));
mbp.setDataHandler(dh);
mbp.setFileName(attachment.substring(attachment.lastIndexOf(File.separator) + 1));
mm.addBodyPart(mbp);
}
return mm;
}
3.内容中包含图片,与上次附件大致相同
private Multipart getContent() throws Exception {
//设置邮件内容
MimeMultipart mm = new MimeMultipart();
BodyPart mbp = new MimeBodyPart();
mbp.setContent(content + "<img src="cid:img1"/>", "text/html;charset=UTF-8");
mm.setSubType("related");
mm.addBodyPart(mbp);
//将需上传的文件转换为二进制
String attachment = "E:/card_01.jpg";
File file = new File(attachment);
if (!file.exists()) {
return mm;
}
BufferedInputStream in = new BufferedInputStream(new FileInputStream(attachment));
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
byte[] attach_bytes = out.toByteArray();
in.close();
out.close();
//转换文件为二进制操作结束
if (attach_bytes != null && attach_bytes.length > 0) {
mbp = new MimeBodyPart();
DataHandler dh = new DataHandler(new ByteArrayDataSource(attach_bytes, "application/octet-stream"));
mbp.setDataHandler(dh);
mbp.setFileName(attachment.substring(attachment.lastIndexOf(File.separator) + 1));
mbp.setHeader("Content-ID", "img1");//指定文件不作为附件而作为文本内容发送
mm.addBodyPart(mbp);
}
return mm;
}
4.会议邀请
private Multipart getContent() throws Exception {
//------VEvent Start----------
//时区
TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
TimeZone timezone = registry.getTimeZone("Asia/Shanghai");
//会议地点
String location = "21-C";
//会议时间
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setTimeZone(timezone);
cal.set(2011, 11 - 1, 16, 10, 30);
DateTime start = new DateTime(cal.getTime());
cal.set(2011, 11 - 1, 16, 11, 00);
DateTime end = new DateTime(cal.getTime());
VEvent vevent = new VEvent(start, end, subject);
vevent.getProperties().add(timezone.getVTimeZone().getTimeZoneId());//时区
vevent.getProperties().add(new Location(location));//会议地点
vevent.getProperties().add(new Summary(subject));//邮件主题
vevent.getProperties().add(new Description(content));//邮件内容
vevent.getProperties().add(new UidGenerator("meeting invite").generateUid());// 设置uid
//与会人
Set<String> emailSet = new HashSet<String>();
emailSet.add(from);
emailSet.add(to);
for (String email : emailSet) {
Attendee attendee = new Attendee(URI.create("mailto:" + email));
attendee.getParameters().add(Role.CHAIR);
attendee.getParameters().add(PartStat.NEEDS_ACTION);
attendee.getParameters().add(Rsvp.TRUE);
attendee.getParameters().add(new Cn(email.substring(0, email.indexOf("@"))));
vevent.getProperties().add(attendee);
}
//--------VEvent Over----------
//--------VAlarm Start----------
//提醒,提前10分钟
VAlarm valarm = new VAlarm(new Dur(0, 0, -10, 0));
//每5分钟提醒一次,提醒三次
valarm.getProperties().add(new Repeat(3));
valarm.getProperties().add(new Duration(new Dur(0, 0, 5, 0)));
//提醒窗口显示的文字信息
valarm.getProperties().add(Action.DISPLAY);
valarm.getProperties().add(new Description("Progress Meeting at 9:30am"));
vevent.getAlarms().add(valarm);//将VAlarm加入VEvent
//--------VAlarm Over-------------
//--------日历对象 Start---------------
Calendar icsCalendar = new Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
icsCalendar.getProperties().add(Method.REQUEST);
icsCalendar.getComponents().add(vevent);//将VEvent加入Calendar
//将日历对象转换为二进制流
CalendarOutputter co = new CalendarOutputter(false);
ByteArrayOutputStream os = new ByteArrayOutputStream();
co.output(icsCalendar, os);
byte[] mailbytes = os.toByteArray();
//--------日历对象 Over------------------
MimeMultipart mm = new MimeMultipart();
mm.setSubType("related");
BodyPart mbp = new MimeBodyPart();
mbp.setContent(mailbytes, "text/calendar;method=REQUEST;charset=UTF-8");
mm.addBodyPart(mbp);
return mm;
}