1、发送邮件带附件
/**
*@param fileName 附件文件名
*@param outputStream 附件的输出流
*@param contentType “application/vnd.ms-excel;charset=UTF-8”这是excel附件,其他附件还要稍微改动下
**/
public Result sendMailWithAttachment(String toEmails, String title, String textContent,
ByteArrayOutputStream outputStream,String fileName,String contentType) throws Exception {
List emailList = Splitter.on(Constant.COMMA).omitEmptyStrings().trimResults().splitToList(toEmails);
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", “smtp.exmail.qq.com”);
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", “smtp”);
// 设置端口号
props.setProperty("mail.smtp.port", "465");
//使用SSL,企业邮箱必需!开启安全协议
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.port", Integer.toString(465));
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");
// 设置环境信息
Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(inviteMailSenderMail, inviteMailSenderMailName, encode));
for (String toEmailItem : emailList) {
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmailItem, toEmailItem, encode));
}
message.setSubject(title, "UTF-8");
MimeMultipart multipart = new MimeMultipart();
// 5. Content: 邮件正文(可以使用html标签)
if(StringUtils.isNotBlank(textContent)){
MimeBodyPart text = new MimeBodyPart();
text.setText(textContent);
multipart.addBodyPart(text);
}
//附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dataHandler2 = new DataHandler(new ByteArrayDataSource(outputStream.toByteArray(),contentType));
attach.setDataHandler(dataHandler2);
attach.setFileName(fileName);
multipart.addBodyPart(attach);
message.saveChanges();
message.setContent(multipart);
// 6. 设置显示的发件时间
message.setSentDate(new Date());
// 7. 保存前面的设置
message.saveChanges();
Transport transport = session.getTransport(smptProtocal);
// 连接邮件服务器
transport.connect(SenderMail, SecurityPwd);//邮箱账号,密码
// 发送邮件
Address[] addressArray = new Address[emailList.size()];
for (int i = 0; i < emailList.size(); i++) {
addressArray[i] = new InternetAddress(emailList.get(i));
}
transport.sendMessage(message, addressArray);
// 关闭连接
transport.close();
return Result.success();
}
2、发送邀请邮件,并加入日历
public Result sendMail(String toEmails, String title, String textContent, MailBean mailBean) throws Exception {
List emailList = Splitter.on(Constant.COMMA).omitEmptyStrings().trimResults().splitToList(toEmails);
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", “smtp.exmail.qq.com”);
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", “smtp”);
// 设置端口号
props.setProperty("mail.smtp.port", "465");
//使用SSL,企业邮箱必需!开启安全协议
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.port", Integer.toString(465));
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");
// 设置环境信息
Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(inviteMailSenderMail, inviteMailSenderMailName, encode));
for (String toEmailItem : emailList) {
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmailItem, toEmailItem, encode));
}
message.setSubject(title, "UTF-8");
MimeMultipart multipart = new MimeMultipart();
// 5. Content: 邮件正文(可以使用html标签)
MimeBodyPart text = new MimeBodyPart();
text.setText(textContent);
multipart.addBodyPart(text);
//vCalendar报文
Date utcStart = new Date(mailBean.getStartTime().getTime()-8*3600*1000);//转UTC时间
Date utcEndd = new Date(mail.getEndTime().getTime()-8*3600*1000);//转UTC时间
String utcStartStr14 = DateUtils.format(utcStart, DateFormatPattern.PATTERN_14);
String utcEndStr14 = DateUtils.format(utcEndd, DateFormatPattern.PATTERN_14);
StringBuffer buffer = new StringBuffer().append("BEGIN:VCALENDAR\n")
.append("PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n")
.append("VERSION:2.0\n")
.append("METHOD:REQUEST\n")
.append("BEGIN:VEVENT\n")
.append("SEQUENCE:1\n");
for (String toEmailItem : emailList) {
buffer.append("ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:" + toEmailItem + "\n");
}
buffer.append("ORGANIZER:MAILTO:" + inviteMailSenderMail + "\n")
.append("DTSTART:"+utcStartStr14.substring(0,8)+"T"+utcStartStr14.substring(8,14)+"Z\n") //结尾Z表示UTC时间
.append("DTEND:"+utcEndStr14.substring(0,8)+"T"+utcEndStr14.substring(8,14)+"Z\n")
.append("LOCATION:"+mailBean.getLocation()+"\n")
.append("UID:" + UUID.randomUUID().toString() + "\n") //如果id相同的话,outlook会认为是同一个会议请求,所以使用uuid。
.append("CATEGORIES:SuccessCentral Reminder\n")
.append("DESCRIPTION:This the description of the meeting.
asd;flkjasdpfi\n\n")
.append("SUMMARY:"+mailBean.getSubject()+"\n" + "PRIORITY:5\n")
.append("CLASS:PUBLIC\n" + "BEGIN:VALARM\n")
.append("TRIGGER:-PT15M\n" + "ACTION:DISPLAY\n")
.append("DESCRIPTION:Reminder\n" + "END:VALARM\n")
.append("END:VEVENT\n" + "END:VCALENDAR");
BodyPart messageBodyPart = new MimeBodyPart();
// 测试下来如果不这么转换的话,会以纯文本的形式发送过去,
//如果没有method=REQUEST;charset=\"UTF-8\",outlook会议附件的形式存在,而不是直接打开就是一个会议请求
messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(buffer.toString(), "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
multipart.addBodyPart(messageBodyPart);
message.saveChanges();
message.setContent(multipart);
// 6. 设置显示的发件时间
message.setSentDate(new Date());
// 7. 保存前面的设置
message.saveChanges();
Transport transport = session.getTransport(smptProtocal);
// 连接邮件服务器
transport.connect(SenderMail, SecurityPwd);//邮箱账号,密码
// 发送邮件
Address[] addressArray = new Address[emailList.size()];
for (int i = 0; i < emailList.size(); i++) {
addressArray[i] = new InternetAddress(emailList.get(i));
}
transport.sendMessage(message, addressArray);
// 关闭连接
transport.close();
return Result.success();
}
注意以上是发送邀请邮件,并加入日历,如果需要更新这个日历信息,那么请求参数中的UID参数需要是同一个,且SEQUENCE参数要大于最开始的值。比如上文用的是1,那么第一次更新要改成2,第二次更新要改成3。
如果要取消该邀请邮件,那么METHOD参数要改成CANCEL,UID参数要保持同一个,SEQUENCE参数同样也要增加,比如上文已经更新两次,sequence变成3了,那么取消的时候要变成4