java发送邮件带附件和图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzlnd/article/details/87862585

import org.apache.commons.httpclient.HttpConnection;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by admin on 2019/2/12.
 */
@Service("SendMail")
public class SendMail {

	private static String imgPath ="/data/app/chador/webapps/chador/img";// 图片保存目录

    public static   void  main(String[] args) throws Exception {
		sendMail();

	}
	public  Boolean sendMail(){
		try {
			Map<String,Object> mapMessage=new HashMap<>();
			String subject="邮件主题";
			mapMessage.put("subject",subject);
			String content="<html><body>" +
						   "<p>尊敬的领导:</p>" +
						   "<p>   您好!以下是运营情况简报,请审阅!</p>" +
						   "<div><h1>1.综述</h1>";
			String imgStr="";
			content+="<img src='cid:allInternet.png'/>";
			imgStr+="allInternet"+",";
			content+="<body></html>";
			mapMessage.put("content",content);
			//附件
			mapMessage.put("imgStr",imgStr);
			sendMessage(mapMessage);
           return true;
		}catch (Exception e){
           e.printStackTrace();
			return false;
		}
	}



	/**
	 *发送邮件
	 */
	public  void sendMessage(Map<String, Object> mapMessage) throws Exception {
		String servicePath = "smtp.caissa.com.cn";   // 服务器地址
		// 准备连接服务器的会话信息
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");       // 使用pop3协议
		props.setProperty("mail.host", servicePath);       // pop3服务器
		props.setProperty("mail.smtp.auth", "true");
		// 创建Session实例对象
		Session session = Session.getInstance(props);
		session.setDebug(true);
		Transport ts=session.getTransport();
		String userName="[email protected]";
		String password="Lad564!@%";
		ts.connect(servicePath,userName,password);
		//创建邮件
		Message message = createMixedMail(session,mapMessage);
		//发送邮件
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();
	}
	/**
	 * @Method: createMixedMail
	 * @Description: 生成一封带附件和带图片的邮件*
	 * @param session
	 * @return
	 * @throws Exception
	 */
	public  MimeMessage createMixedMail(Session session, Map<String,Object> mapMessage) throws Exception {
		//创建邮件
		MimeMessage message = new MimeMessage(session);

		//设置邮件的基本信息
		message.setFrom(new InternetAddress("发送人邮箱"));
		String[] toUserNames="邮箱地址1,邮箱地址2".split(",");
		Address[] tos = new InternetAddress[toUserNames.length];
		if(toUserNames!=null && toUserNames.length>0){
			for(int i=0;i<toUserNames.length;i++){
			     tos[i]=new InternetAddress(toUserNames[i]);
			}
			message.setRecipients(Message.RecipientType.TO, tos);
		}else {
			tos[0]=new InternetAddress("邮箱地址");
		}
		message.setSubject(mapMessage.get("subject").toString());

		//正文
		MimeBodyPart text = new MimeBodyPart();
		text.setContent(mapMessage.get("content"),"text/html;charset=UTF-8");


//		message.setContent(mapMessage.get("content"),"text/html;charset=UTF-8");

		String imgStr=mapMessage.get("imgStr").toString();


		//描述关系:正文和图片
		MimeMultipart mp1 = new MimeMultipart();
		mp1.addBodyPart(text);


		//描述关系:正文和附件
		MimeMultipart mp2 = new MimeMultipart();
		if(imgStr!=null && !"".equals(imgStr)){
			String[] imgStrs=imgStr.split(",");
			for(int i=0;i<imgStrs.length;i++){
				String imgUrl=imgPath+"/"+imgStrs[i]+".png";
				String contentId=imgStrs[i]+".png";
				//图片1
				MimeBodyPart image = new MimeBodyPart();
				image.setDataHandler(new DataHandler(new FileDataSource(imgUrl)));
				image.setContentID(contentId);

				//附件1
				MimeBodyPart attach = new MimeBodyPart();
				DataHandler dh = new DataHandler(new FileDataSource(imgUrl));
				attach.setDataHandler(dh);
				attach.setFileName(dh.getName());

				//描述关系:正文和图片
				mp1.addBodyPart(image);
				mp1.setSubType("related");

				//描述关系:正文和附件
				mp2.addBodyPart(attach);



			}
		}
		//代表正文的bodypart
		MimeBodyPart content = new MimeBodyPart();
		content.setContent(mp1);
		mp2.addBodyPart(content);
		mp2.setSubType("mixed");


		message.setContent(mp2);
		message.saveChanges();
		//将邮件内容保存到本地的位置
//		message.writeTo(new FileOutputStream("D:\\mail"));
		//返回创建好的的邮件
		return message;
	}




}

猜你喜欢

转载自blog.csdn.net/lzlnd/article/details/87862585