发送带附件的邮件 java

         在此分享互相交流学习,如有问题请指正

javax.mail.* 下载地址:http://download.csdn.net/detail/daohaode123/8394273



package com.zjl;

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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.junit.Test;

public class Email {
	/**
	 * 发送带附件的邮件
	 * @param formAddr
	 * @param toAddr
	 * @param subject
	 * @param content
	 * @param affixPath 附件路径
	 * @return
	 * @throws Exception 
	 */
	public boolean sendEmailIncludingAffix(String host, String formAddr, String toAddr,
			String subject, String content, String affixPath) throws Exception{
		Properties prop = new Properties();
		prop.put("mail.smtp.auth", false);//不进行邮件用户名 、密码验证
		prop.put("mail.smtp.host", host);
		
		Session session = Session.getDefaultInstance(prop);
		session.setDebug(true);//此处会在控制台打印发送邮件的调用过程
		MimeMessage message = new MimeMessage(session);
		try{
			message.setFrom(new InternetAddress(formAddr));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
			message.setSentDate(new Date());
			message.setSubject(subject);
			
			Multipart mutiPart = new MimeMultipart();
			// 添加邮件
			BodyPart contentpart = new MimeBodyPart();
			contentpart.setText(content);
			mutiPart.addBodyPart(contentpart);
			
			//添加附件
			BodyPart bp = new MimeBodyPart();
			DataSource datasource = new FileDataSource(affixPath);
			bp.setDataHandler(new DataHandler(datasource));
			bp.setFileName(datasource.getName());
			mutiPart.addBodyPart(bp);
			
			message.setContent(mutiPart);
			//保存邮件
			message.saveChanges();
			//发送邮件
			Transport.send(message);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
	}
	
	@Test
	public void Test(){
		try {
			boolean isSucess = sendEmailIncludingAffix("8.99.5.116","123@qq.com","234@qq.com","主题","测试发邮件","D:\\email.xls");
			if(isSucess){
				System.out.println("发送成功");
			}else{
				System.out.println("登录失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值