• 2024-11-23
宇哥博客 后端开发 Java发送邮件,多个收件人、抄送、图片

Java发送邮件,多个收件人、抄送、图片

Java使用mail.jar包发送邮件,支持多个收件人、多个抄送人、密送,可配多张图片。

package com.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class SendMail {

	//测试
	String emailUser="xxx@xxx.cn";
	String emailPassword="xxxx";
	
	
	InetAddress mailHost;
    InetAddress ourselves;
    BufferedReader in;
    PrintWriter out;
    String strmail;
    String initialID;
    String welcome;
    String sendOk;
    String recipientOk;
    String dataOk;
    String acceptedOk;

    
    /**
     * 发送邮件
     * 
     * @param to收件人,多个收件人“,”符号隔开
     * @param cc抄送,多个收件人“,”符号隔开
     * 
     * @param imagePath图片完整路径
     * @param attachments附件(这个先空到这)
     * 
     * @throws UnsupportedEncodingException 
     */
    public String sendEmailV2(String to,String subject,String content,String cc,String bcc,List imagePath, File[] attachments) throws AddressException, MessagingException, UnsupportedEncodingException{

		String from = emailUser ;
		
		String mailhost = "smtp.exmail.qq.com";
		boolean debug = false;
		String username = emailUser;
		String password = emailPassword; //
		Properties props = System.getProperties();
		props.put("mail.smtp.auth", "true");
		
		SMTPAuth auth = new SMTPAuth(username, password);
		// could use Session.getTransport() and Transport.connect()
		// assume we're using SMTP
		if (mailhost != null)
			props.put("mail.smtp.host", mailhost);

		// Get a Session object
		Session session = Session.getDefaultInstance(props, auth);
		if (debug)
			session.setDebug(true);

		// construct the message
		Message msg = new MimeMessage(session);
		if (from != null)
			msg.setFrom(new InternetAddress(from));
		else
			msg.setFrom();

		//msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
		//支持多个收件人
		if(to.indexOf(",")!=-1){
			String to2[]=to.split(",");
			InternetAddress[] adr = new InternetAddress[to2.length];
			for (int i = 0; i < adr.length; i++) {
				adr[i] = new InternetAddress(to2[i]);
			}
			msg.setRecipients(Message.RecipientType.TO, adr);
		}else{
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
		}
		if (cc != null){
			//msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
			if(cc.indexOf(",")!=-1){
				//多个
				String cc2[]=cc.split(",");
				InternetAddress[] adr = new InternetAddress[cc2.length];
				for (int i = 0; i < cc2.length; i++) {
					adr[i] = new InternetAddress(cc2[i]);
				}
				// Message的setRecipients方法支持群发。。注意:setRecipients方法是复数和点 到点不一样
				msg.setRecipients(Message.RecipientType.CC, adr);
			}else{
				msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
			}
		}
			
		if (bcc != null)
			msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

		msg.setSubject(subject);

		MimeBodyPart mbp1 = new MimeBodyPart();
		String html = content;
		mbp1.setContent(html, "text/html;charset=UTF-8");

		MimeMultipart mp = new MimeMultipart("related");// alternative
		mp.addBodyPart(mbp1);
		
		if(imagePath != null){
			for (int i = 0; i < imagePath.size(); i++) {
				
				mp.addBodyPart(createImageMimeBodyPart(imagePath.get(i).toString() ));
			}
		}
		
		msg.setContent(mp);

		msg.setSentDate(new Date());
		Transport.send(msg);
		
		//System.out.println("****"+mp.getCount());
		System.out.println("\n"+to+" 发送成功");
		return "";
	}
    
    //添加内嵌图片
    private MimeBodyPart createImageMimeBodyPart(String imagePath) throws MessagingException, UnsupportedEncodingException{
        FileDataSource fds=new FileDataSource(imagePath);
        MimeBodyPart mbp=new MimeBodyPart();  
        DataHandler dh=new DataHandler(fds);
        mbp.setDataHandler(dh);  
        //设置对应的资源文件的唯一标识符,即 MIME 协议对于邮件的结构组织格式中的 Content-ID 头字段;
        mbp.setHeader("Content-ID", new File(imagePath.trim()).getName() );
        mbp.setFileName(fds.getName());  
        return mbp;
    }
    
    
    
    public static void main(String[] args){
    	
    	SendMail sd=new SendMail();
    	
    	
    	String to="xxx@xxx.cn";
    	String subject="xxxxxx";
    	
    	
    	List imagePath=new ArrayList();
    	imagePath.add("D:\\1.png");
    	imagePath.add("D:\\2.png");
    	
        String content="测试内容<img src=\"cid:1.png\"  /><br/><img src=\"cid:2.png\"  />";
    	
    	try {
			sd.sendEmailV2(to, subject, content, null, null, imagePath, null);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
    
}




class SMTPAuth extends javax.mail.Authenticator {
	private String user, password;

	public SMTPAuth(String u, String p) {
		user = u;
		password = p;
	}
	public void getuserinfo(String getuser, String getpassword) {
		user = getuser;
		password = getpassword;
	}
	protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
		return new javax.mail.PasswordAuthentication(user, password);
	}
}

mail.jar包下载链接: https://pan.baidu.com/s/1RD-wS5wSAx9IinYZHJDH_Q 提取码: tdcp

本文来自网络,不代表本站立场,转载请注明出处。https://www.ygbks.com/1087.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

返回顶部