java mail共享网盘附件发送邮件

6 篇文章 0 订阅

需求背景:

用户从共享网盘选择文件作为邮件附件发送;需要:文件拷贝,共享文件读取,带附件的邮件发送;或直接发送远程附件(优);先贴代码,后续在逐个对功能代码块作拆分讲解!!

<!-- Setting for mail -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host">
            <value>mailserv.mmm.com</value>
        </property>
        <property name="username"><value>发邮件用的邮箱</value></property>
        
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">false</prop>
                <prop key="mail.smtp.timeout">25000</prop>
            </props>
        </property>
    </bean>
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
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.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

public class MailUtil {
	private JavaMailSender mailSender;

	public void sendEmail(String toAddress, String fromAddress, String subject, String msgBody) {
		try {

			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "UTF-8");
			mimeMessage.setContent(msgBody, "text/html;charset=utf8");
			helper.setFrom(fromAddress);
			helper.setTo(toAddress);
			helper.setSubject(subject);
			mailSender.send(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sendAttachement2Email(String toAddress, String fromAddress, String subject, File localFile) {
		try {

			MimeMessage mimeMessage = mailSender.createMimeMessage();
			// 添加附件
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			mimeMessageHelper.setTo(toAddress);
			mimeMessageHelper.setFrom(fromAddress);
			mimeMessageHelper.setSubject(subject);

			mimeMessageHelper.setText("<html><head></head><body><h1>hello!!zhangfl</h1></body></html>", true);
			FileSystemResource fsr = new FileSystemResource(localFile);
			mimeMessageHelper.addAttachment(localFile.getName(), fsr);

			mailSender.send(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendRemotAttachement2Email(String toAddress, String fromAddress, String subject) {
		try {
			String remotePath = "参数待提供";
			String userName = " 参数待提供";
			String userPassword = "参数待提供";
			SmbFile smbFile = getRemoteFile(remotePath, userName, userPassword);

			File localFile;
			if (smbFile.isDirectory()) {
				for (SmbFile f : smbFile.listFiles()) {
					if (f.isDirectory()) {
						continue;
					}
					localFile = copyRemoteFile(f);
					sendAttachement2Email(toAddress, fromAddress, subject, localFile);
					//sendRemoteFile2Mail(toAddress, fromAddress, subject, smbFile); 远程文件方式推荐
				}

			} else if (smbFile.isFile()) {
				localFile = copyRemoteFile(smbFile);
				sendAttachement2Email(toAddress, fromAddress, subject, localFile);
				// sendRemoteFile2Mail(toAddress, fromAddress, subject, smbFile);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 将远程文件复制为本地文件 **/
	private File copyRemoteFile(SmbFile remoteFile) throws IOException {

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		BufferedReader in = null;
		BufferedWriter out = null;

		String fileName = remoteFile.getName();
		File localFile = new File(fileName);
		try {
			bis = new BufferedInputStream(new SmbFileInputStream(remoteFile));
			bos = new BufferedOutputStream(new FileOutputStream(localFile));
			String temp;
			in = new BufferedReader(new InputStreamReader(bis, "utf-8"));
			out = new BufferedWriter(new OutputStreamWriter(bos));
			while ((temp = in.readLine()) != null) {
				out.write(temp);
			}
		} catch (SmbException | MalformedURLException | UnknownHostException | UnsupportedEncodingException
				| FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			in.close();
			out.close();
			bis.close();
			bos.close();
		}

		return localFile;

	}

	/** 获取远程文件 **/
	private SmbFile getRemoteFile(String remotePath, String userName, String userPassword) throws IOException {
		System.setProperty("jcifs.smb.client.dfs.disabled", "true");

		NtlmPasswordAuthentication auth;
		SmbFile smbFile;
		String remoteURL = "smb://" + remotePath;// 需要正则验证解析路径
		if (null != userName && !"".equals(userName) && null != userPassword && !"".equals(userPassword)) {
			auth = new NtlmPasswordAuthentication("", userName, userPassword);
			smbFile = new SmbFile(remoteURL, auth);
		} else {
			smbFile = new SmbFile(remoteURL);
		}

		return smbFile;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 发送远程文件邮件
	 * 
	 * @param to      收件人
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * @param smbFile 远程文件
	 */
	private void sendRemoteFile2Mail(String toAddress, String fromAddress, String subject, SmbFile smbFile) {
		String content = "这是正文";
		try {

			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(fromAddress);
			helper.setTo(toAddress);
			helper.setSubject(subject);

			message.setContent(getMultipart(content, smbFile));

			mailSender.send(message);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取Multipart对象,包含正文内容、附件、文件名
	 * 
	 * @return
	 */
	private Multipart getMultipart(String content, SmbFile smbFile) throws Exception {
		Multipart multipart = new MimeMultipart();

		// 向multipart中添加正文
		BodyPart contentBody = new MimeBodyPart();
		contentBody.setContent(content, "text/html;charset=UTF-8");
		multipart.addBodyPart(contentBody);

		// 向multipart中添加远程附件
		MimeBodyPart fileBody = new MimeBodyPart();
		DataSource source = new ByteArrayDataSource(new SmbFileInputStream(smbFile), "application/html");
		fileBody.setDataHandler(new DataHandler(source));
		fileBody.setFileName(MimeUtility.encodeText(smbFile.getName(), "UTF-8", "B"));
		multipart.addBodyPart(fileBody);

		return multipart;
	}

}


    
    

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值