java发送带附件的电子邮件

随着业务的复杂度,一般意义上的电子邮件无法满足需求,有些邮件需要附带 url附件文件。

具体公共类 MailUtils.java

如下

package com;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MailUtils {
	
	private String host;
	private String port;
	private String user;
	private String password;
	private String userName;
	private String userNm_charset;

	static Logger logger = LoggerFactory.getLogger(MailUtils.class);

	/**
	 * 发件,信息初始化
	 * @param host 邮件SMTP服务器
	 * @param port SMTP服务器端口号
	 * @param user 发件人邮箱
	 * @param password 发件人邮箱密码
	 * @param userName 发件人名字
	 */
	public MailUtils(String host,String port, String user, String password,String userName,String userNm_charset){
	    this.host = host;
		this.port = port;
	    this.user = user;
	    this.password = password;
		this.userName = userName;
		this.userNm_charset = userNm_charset;
	}

	/**
	 * 开始发件
	 *
	 * 说明 1,本地文件(fileName、in、inType 必须同时有值),
	 * 	   2,网路文件(fileName、fpPdf 必须同时有值)
	 *
	 * @param title 邮件标题
	 * @param toMail 收件人邮箱
	 * @param content 邮件正文
	 * @param fileName 附件名
	 * @param in 附件文件流
	 * @param inType 附件文件类型
	 * @param fpPdf 附件url
	 * @param ccList 抄送人邮箱
	 * @return
	 */
	public boolean sendMail(String title, String toMail, String content,String fileName, InputStream in,String inType,String fpPdf,String ccList) {
	    boolean isFlag = false;
	    try {
	        Properties props = new Properties();
	        props.put("mail.smtp.host", host); // 指定SMTP服务器
	        props.put("mail.smtp.port", port); // 指定SMTP服务器端口号
	        props.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证

			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);// 设置信任所有的主机
			props.put("mail.smtp.ssl.enable", "true");
			props.put("mail.smtp.ssl.socketFactory", sf);
			//props.put("mail.smtp.timeout", "25000");//超时时间
			
	        Session session = Session.getDefaultInstance(props);
	        session.setDebug(false);
	
	        MimeMessage message = new MimeMessage(session);
	        try {
	            //指定发送人
				if(userName!=null && !"".equals(userName)){
					if(userNm_charset==null || "".equals(userNm_charset)){
						userNm_charset = "utf-8";
					}

					message.setFrom(new InternetAddress(user,userName,userNm_charset));
				}else{
					message.setFrom(new InternetAddress(user));
				}
	            //指定接收人
	            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
	            //指定抄送人
	            if(ccList!=null || !"".equals(ccList)){
	                message.addRecipients(Message.RecipientType.CC,ccList);
	            }
	            //设置标题
	            message.setSubject(title,"UTF-8");
	            message.addHeader("charset", "UTF-8");
	
	            /*添加正文内容*/
	            //一个Multipart对象包含一个或多个bodypart对象,组成邮件正文
	            Multipart multipart = new MimeMultipart();
	
	            MimeBodyPart contentPart = new MimeBodyPart();
	            contentPart.setText(content,"UTF-8");
	            contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
	            multipart.addBodyPart(contentPart);
	
	            /*添加附件*/
	            if(in != null) {
	                MimeBodyPart fileBody = new MimeBodyPart();
	                DataSource source = new ByteArrayDataSource(in, inType);//"application/msexcel"
	                fileBody.setDataHandler(new DataHandler(source));
	                // 中文乱码问题
	                fileBody.setFileName(MimeUtility.encodeText(fileName));
	                multipart.addBodyPart(fileBody);
	            }
	            if(in == null && fpPdf != null) {
	            	MimeBodyPart fileBody = new MimeBodyPart();
	            	URL url = new URL(fpPdf);
	                DataSource dataSource=new URLDataSource(url);
	                DataHandler dataHandler=new DataHandler(dataSource);
	                fileBody.setDataHandler(dataHandler);
	                // 中文乱码问题
	                fileBody.setFileName(MimeUtility.encodeText(fileName));
	                multipart.addBodyPart(fileBody);
	            }
	
	            message.setContent(multipart);
	            message.setSentDate(new Date());
	            message.saveChanges();
	            Transport transport = session.getTransport("smtp");            
	            transport.connect(host, user, password);
	            transport.sendMessage(message, message.getAllRecipients());
	            transport.close();
	            isFlag = true;
	            logger.info(Calendar.getInstance().getTime()+":#Send mail to"+toMail+"success #");
	        } catch (Exception e) {
	              logger.info(Calendar.getInstance().getTime()+":#Send mail to"+toMail+"error #");
	            logger.info(e.toString());
	            e.printStackTrace();
	            isFlag = false;
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return isFlag;
	}
}

引用公共类

如下:

logger.info("发送邮件------>>>userEmail:{},charset:{}",userEmail,mail_userNm_charset);
            MailUtils mailUtils = new MailUtils(mail_host,mail_port,mail_user,mail_pass,mail_userNm,mail_userNm_charset);

            String title = "订单"+orderNo+"发票";
            //收件人
            String toMail = userEmail;
            //正文
            String content = "<h1 align=\"center\">迪信通电子发票</h1>"
                    +"<p>你好:</p>"
                    +"<p style=\"padding-left:2em;\">你申请的电子发票,详见<font style=\"font-weight:bold;color:#0000cc;font-size:20px\">附件</font>。</p>"
                    +"<p style=\"padding-left:2em;\">如未能打开,请<a target=\"_blank\" href=\""+eleInvoice.getFpUrl()+"\">点击链接</a>查看:"+eleInvoice.getFpUrl()+"</p>";
            //附件文件名
            String fileName  = "订单"+orderNo+"电子发票.pdf";
            //附件文件流
            InputStream in = null;
            //附件文件类型
            String inType = "";
            //抄送
            String ccList = "";
            mailUtils.sendMail(title, toMail, content, fileName, in,inType,eleInvoice.getFpUrl(), ccList);

效果图:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送超大附件邮件可以通过使用JavaMail API来实现。以下是一个简单的示例: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String [] args) { // 收件人电子邮箱 String to = "[email protected]"; // 发件人电子邮箱 String from = "[email protected]"; // 指定发送邮件的主机为 smtp.gmail.com String host = "smtp.gmail.com"; // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); // 获取默认的 Session 对象。 Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password");//发件人邮箱用户名和密码 } }); try { // 创建默认的 MimeMessage 对象。 MimeMessage message = new MimeMessage(session); // 设置 From: 头部头字段 message.setFrom(new InternetAddress(from)); // 设置 To: 头部头字段 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置主题 message.setSubject("This is the Subject Line!"); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 填充消息 messageBodyPart.setText("This is message body"); // 创建多重消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); String filename = "file.txt";//附件文件名 DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // 发送完整消息 message.setContent(multipart); // 发送消息 Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } } ``` 在上面的示例中,我们创建了一个包含文本和附件的多重消息。附件可以是任何类型的文件,只需指定正确的文件路径即可。请注意,在发送超大附件邮件时,您需要确保您的邮件服务器支持该大小的邮件,并且接收方的邮箱也支持接收超大附件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值