javaMail 邮件发送带附件

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
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;
import javax.mail.internet.MimeUtility;

public class SendMailDemo1 {


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

		Properties props = new Properties();
		//设置协议
		props.setProperty("mail.transport.protocol", "smtp");
		//设置服务器
		props.setProperty("mail.host", "smtp.163.com");
		//请求身份认证
		props.setProperty("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress("发件人邮箱"));//发件人
		message.setRecipients(MimeMessage.RecipientType.TO, "收件人邮箱");//收件人
		message.setSubject("这是一封java邮件");
		MimeBodyPart textPart = new MimeBodyPart();
		textPart.setContent("hello <img src='cid:map'/>world 这是一封java邮件", "text/html;charset=utf-8");
		MimeBodyPart imagePart = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource("F:/素材/地图.jpg"));
		imagePart.setDataHandler(dh);
		imagePart.setContentID("map");//设置cid
		
		MimeMultipart mpart = new MimeMultipart();
		mpart.addBodyPart(textPart);
		mpart.addBodyPart(imagePart);
		mpart.setSubType("related");//设置关系
		
		MimeBodyPart textimagePart = new MimeBodyPart();
		textimagePart.setContent(mpart);
		
		//添加附件
		MimeBodyPart attachmentPart = new MimeBodyPart();
		dh = new DataHandler(new FileDataSource("C:/Users/Administrator/Desktop/计算机组成原理课件.zip"));
		String fileName = dh.getName();//获取附件文件名,避免出现乱码
		attachmentPart.setDataHandler(dh);
		//手工设置附件名,注意编码问题
		attachmentPart.setFileName(MimeUtility.encodeText(fileName));
		
		MimeMultipart mpart2 = new MimeMultipart();
		mpart2.addBodyPart(textimagePart);
		mpart2.addBodyPart(attachmentPart);
		mpart2.setSubType("mixed");//设置关系
		message.setContent(mpart2);
		message.saveChanges();//保存邮件改变
		//发送邮件
		Transport ts = session.getTransport();
		ts.connect("用户名", "密码");//连接用户
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();
		
		
		
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值