1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > JavaMail(三)——发送HTML格式带附件的邮件

JavaMail(三)——发送HTML格式带附件的邮件

时间:2020-04-05 04:01:40

相关推荐

JavaMail(三)——发送HTML格式带附件的邮件

代码如下:

package pany;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.*;import java.util.Date;import java.util.Properties;/*** Created by lining on /5/26.*/public class HtmlMessageSender {private static final String nickname = "李宁";private static final String username = "152****1370@";private static final String password = "******";private static final String protocol = "smtp";private static final String host = "";private static final String port = "25";public static void main(String[] args) {String to = "******9997@;******9267@";String subject = "文本邮件主题";String body = "<h4>HTML+附件的邮件测试!!!</h4></br><a href=>" + "点击跳转</a>";String attach = "D:\\TXT\\CMD命令.txt;D:\\TXT\\常用MYSQL语句.txt";Email email = new Email();email.setToEmails(to.split(";"));email.setSubject(subject);email.setContent(body);email.setAttachments(attach.split(";"));if (sendEmail(email)) {System.out.println("邮件发送成功!");} else {System.out.println("邮件发送失败!请及时解决!");}}/*** 发送邮件* @param email 邮件信息实体* @return 是否发送成功 TRUE 发送成功 FALSE 发送失败*/public static boolean sendEmail(Email email) {try {// 创建Session实例对象Session session = createSession();// 创建MimeMessage实例对象MimeMessage message =createMessage(session, email);// 发送邮件System.out.println("发送邮件中......");Transport.send(message);return true;} catch (Exception e) {System.out.println("发送邮件异常==》");e.printStackTrace();return false;} finally {System.out.println("邮件发送结束...");}}/*** 创建与邮件服务器的会话对象* @return 服务器的会话对象*/public static Session createSession() {// 封装属性参数Properties props = new Properties();props.setProperty("mail.transport.protocol", protocol);props.setProperty("mail.smtp.host", host);props.setProperty("mail.smtp.port", port);props.setProperty("mail.smtp.auth", "true"); // 是否需要验证设置为TRUE,使用授权码发送邮件需要验证// 获取与服务器的会话Session对象Session session = Session.getInstance(props, new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {// 登陆账号及密码,密码需要是第三方授权码return new PasswordAuthentication(username, password);}});return session;}/*** 创建邮件的核心内容* @param session 与服务器交互的会话对象* @param email 邮件实体* @return 生成的MimeMessage实例对象* @throws Exception*/public static MimeMessage createMessage(Session session, Email email) throws Exception{// 创建MimeMessage实例对象MimeMessage message = new MimeMessage(session);// 设置发件人if (!nickname.isEmpty()) {// 自定义发件人昵称message.setFrom(new InternetAddress(MimeUtility.encodeText(nickname) + " <" + username + ">"));} else {message.setFrom(new InternetAddress(username));}// 设置收件人String[] toEmails = email.getToEmails();if (toEmails != null && toEmails.length != 0) {InternetAddress[] internetAddressTO = new InternetAddress[toEmails.length];for (int i = 0; i < toEmails.length; i++) {internetAddressTO[i] = new InternetAddress(toEmails[i]);}message.setRecipients(Message.RecipientType.TO, internetAddressTO);}// 设置密送人String[] bccEmails = email.getBccEmails();if (bccEmails != null && bccEmails.length != 0) {InternetAddress[] internetAddressBCC = new InternetAddress[bccEmails.length];for (int i = 0; i < bccEmails.length; i++) {internetAddressBCC[i] = new InternetAddress(bccEmails[i]);}message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);}// 设置抄送人String[] ccEmails = email.getCcEmails();if (ccEmails != null && ccEmails.length != 0) {InternetAddress[] internetAddressCC = new InternetAddress[ccEmails.length];for (int i = 0; i < ccEmails.length; i++) {internetAddressCC[i] = new InternetAddress(ccEmails[i]);}message.setRecipients(, internetAddressCC);}// 设置发生日期message.setSentDate(new Date());// 设置邮件主题message.setSubject(email.getSubject());/* 创建用于组合邮件正文和附件的MimeMultipart对象 */MimeMultipart multipart = new MimeMultipart();// 设置HTML内容MimeBodyPart content = createContent(email.getContent());multipart.addBodyPart(content);// 设置附件String[] attachments = email.getAttachments();if (attachments != null && attachments.length != 0) {for (String filename: attachments) {MimeBodyPart attachPart = createAttachment(filename);multipart.addBodyPart(attachPart);}}// 将组合的MimeMultipart对象设置为整个邮件的内容,要注意调用saveChanges方法进行更新message.setContent(multipart);// 保存并生成最终的邮件内容message.saveChanges();return message;}/*** 创建HTML格式的邮件内容* @param body 邮件内容* @return 邮件内容实体* @throws Exception*/public static MimeBodyPart createContent(String body) throws Exception {/* 创建代表组合MIME消息的MimeMultipart对象和该对象保存到的MimeBodyPart对象 */MimeBodyPart content = new MimeBodyPart();// 创建一个MImeMultipart对象MimeMultipart multipart = new MimeMultipart();// 创建一个表示HTML正文的MimeBodyPart对象,并将它加入到前面的创建的MimeMultipart对象中MimeBodyPart htmlBodyPart = new MimeBodyPart();htmlBodyPart.setContent(body, "text/html;charset=UTF-8");multipart.addBodyPart(htmlBodyPart);// 将MimeMultipart对象保存到MimeBodyPart对象中content.setContent(multipart);return content;}/*** 创建邮件中的附件* @param filepath 附件的路径* @return 生成的附件对象* @throws Exception*/public static MimeBodyPart createAttachment(String filepath) throws Exception {/* 创建一个表示附件的MimeBodyPart对象,并加入附件内容以及相应的信息 */MimeBodyPart attachPart = new MimeBodyPart();// FileDataSource用于读取文件数据,并返回代表数据的输入输出流和数据的MIME类型FileDataSource fileDataSource = new FileDataSource(filepath);// DataHandler类用于封装FileDataSource对象,并为应用程序提供访问数据的接口attachPart.setDataHandler(new DataHandler(fileDataSource));// 设置附件名称,MimeUtility.encodeText可以处理乱码问题attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));return attachPart;}}

运行结果:

点击邮件中的“点击跳转”即可打开Apache的主页:/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。