Java发送邮件,抄送,附加(file文件,url中获取),html

21 篇文章 0 订阅
15 篇文章 0 订阅

maven

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-email</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.7.16</version>
    </dependency>

代码


import cn.hutool.core.collection.CollectionUtil;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
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 org.apache.commons.lang3.StringUtils;


public class EmailSendUtil {

	private static final String host = ""; //host
	private static final String port = ""; //port
	private static final String username = "";//邮箱账号
	private static final String password = "";//邮箱密码
	private static final String protocol = "";//协议

	/**
	 * @param email    收件人
	 * @param copys    抄送人
	 * @param subject  主题
	 * @param content  内容
	 * @param files    附加(文件类型)
	 * @param fileUrls 附加(url类型)
	 */

	public void send(String email, List<String> copys, String subject, String content,
		List<File> files, List<String> fileUrls) {
		Transport transport = null;
		try {
			Properties props = System.getProperties();
			//设置用户的认证方式
			props.setProperty("mail.smtp.auth", "true");
			//设置传输协议
			props.setProperty("mail.transport.protocol", protocol);
			//设置发件人的SMTP服务器地址
			props.setProperty("mail.smtp.host", host);
			//端口
			props.setProperty("mail.smtp.port", port);
			//使用ssl
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			Session session = Session.getInstance(props, null);
			MimeMessage mimeMessage = new MimeMessage(session);
			InternetAddress mailFrom = new InternetAddress(username);
			InternetAddress mailTo = new InternetAddress(email);
			//发件箱
			mimeMessage.setFrom(mailFrom);
			//收件箱
			mimeMessage.setRecipient(RecipientType.TO, mailTo);
			//回复地址
			mimeMessage.setReplyTo(new Address[]{mailFrom});
			//邮件标题
			mimeMessage.setSubject(subject);
			//发件人
			mimeMessage.setSender(mailFrom);
			//抄送
			if (CollectionUtil.isNotEmpty(copys)) {
				Address[] addresses = new Address[copys.size()];
				for (int i = 0; i < copys.size(); i++) {
					String copy = copys.get(i);
					addresses[i] = new InternetAddress(copy);
				}
				mimeMessage.addRecipients(RecipientType.CC, addresses);
			}
			//附加
			MimeMultipart mimeMultipart = new MimeMultipart();
			//内容
			if (StringUtils.isNotBlank(content)) {
				BodyPart textPart = new MimeBodyPart();
				textPart.setContent(content, "text/html;charset=UTF-8");
				mimeMultipart.addBodyPart(textPart);
			}
			//文件附加
			if (CollectionUtil.isNotEmpty(files)) {
				files.forEach(file -> {
					BodyPart fileBodyPart = new MimeBodyPart();
					try {
						//构造附件一的数据源
						FileDataSource fileDataSource = new FileDataSource(file);
						//数据处理
						DataHandler dataHandler = new DataHandler(fileDataSource);
						fileBodyPart.setDataHandler(dataHandler);
						fileBodyPart.setFileName(file.getName());
						mimeMultipart.addBodyPart(fileBodyPart);
					} catch (MessagingException e) {
						throw new RuntimeException(e);
					}

				});
			}
			//图片附加
			if (CollectionUtil.isNotEmpty(fileUrls)) {
				for (int i = 0; i < fileUrls.size(); i++) {
					String urlPath = fileUrls.get(i);
					//邮件中包含网络附件
					URL url = null;
					try {
						url = new URL(urlPath);
						DataHandler dataHandler = new DataHandler(url);
						BodyPart urlBodyPart = new MimeBodyPart();
						urlBodyPart.setDataHandler(dataHandler);
						urlBodyPart.setFileName(urlPath);
						mimeMultipart.addBodyPart(urlBodyPart);
					} catch (MalformedURLException e) {
						throw new RuntimeException(e);
					}
				}
			}
			//邮件内容
			mimeMessage.setContent(mimeMultipart);
			transport = session.getTransport(protocol);
			transport.connect(host, username, password);
			//发送邮件
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (Objects.nonNull(transport)) {
					transport.close();
				}
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
	}



}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用JavaMail API来发送带有多个抄送人的邮件。以下是一个简单的示例代码: ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { // 收件人电子邮箱 String to = "recipient@example.com"; // 抄送人电子邮箱列表 String[] cc = {"cc1@example.com", "cc2@example.com"}; // 发件人电子邮箱 String from = "sender@example.com"; // 发件人电子邮箱密码 String password = "password"; // 指定发送邮件的主机为 smtp.gmail.com String host = "smtp.gmail.com"; // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.port", "587"); // 获取默认的 Session 对象 Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置抄送人 for (int i = 0; i < cc.length; i++) { message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i])); } // 设置邮件主题 message.setSubject("This is the Subject Line!"); // 设置邮件正文 message.setText("This is actual message"); // 发送邮件 Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } } } ``` 在上面的示例,我们使用了`message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]))`来添加多个抄送人。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值