java发邮件

/**
 * 邮件发送
 */
/**
 * @author 
 */
public class EmailServiceImpl {
	private String sendHost = null;// 发送服务器地址
	private String receiveHost = null;// 接受服务器地址
	private String user = null;// 邮件服务器账号
	private String password = null;// 邮件服务器账号密码
	private String from = null;// 来源地址
	
	
	/**
	 * 获得配置文件内容
	 * @author 
	 */
	public  void Proper() {
		Properties prop = new Properties();
		String file = this.getClass().getResource("/emailserver.properties").getFile();
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			prop.load(in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		sendHost=prop.getProperty("emailserver.sendHost");
		receiveHost = prop.getProperty("emailserver.receiveHost");
		user=prop.getProperty("emailserver.user");
		password=prop.getProperty("emailserver.password");
		from=prop.getProperty("emailserver.from");
		//System.out.println(password);
		//System.out.println("==sendHost="+sendHost+"==receiveHost=="+receiveHost+"===user==="+user+"===password=="+password);
		
	}

	/**
	 * @return the sendHost
	 */
	public String getSendHost() {
		return sendHost;
	}

	/**
	 * @param sendHost
	 *            the sendHost to set
	 */
	public void setSendHost(String sendHost) {
		this.sendHost = sendHost;
	}

	/**
	 * @return the receiveHost
	 */
	public String getReceiveHost() {
		return receiveHost;
	}

	/**
	 * @param receiveHost
	 *            the receiveHost to set
	 */
	public void setReceiveHost(String receiveHost) {
		this.receiveHost = receiveHost;
	}

	/**
	 * @return the user
	 */
	public String getUser() {
		return user;
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(String user) {
		this.user = user;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	
	/* 发送邮件时是否进行身份验证 */
	private boolean authFlag = true;

	/* 发送邮件是否需要代理 */
	private boolean proxyFlag = false;
	/* 其他设置 */
	private boolean restFlag = false;
	
	/**
	 * 设置邮件发信人、收信人、抄送、密送、邮件标题、邮件内容、附件的文件名称(包括路径) 同时生成Session、Message,并且调用发送邮件
	 */
	public synchronized int sendEmailNow(String to,String cc,String subject, String body, String attchFile)

	{
		//System.out.println("hello");
		Proper();
		int successFlag = 0;
		int m_result;
		try {
			Properties props = System.getProperties(); // Properties用来将props传给MAIL
														
			Session session = null; // 创建Session对象

			props.put("mail.smtp.host", sendHost);
			if (authFlag) {
				props.put("mail.smtp.auth", "true");
			} else {
				props.put("mail.smtp.auth", "");
			}
			session = Session.getInstance(props, null);

			if (restFlag) {
				session.setDebug(true);
			}
			/** 创建邮件MESSAGE */
			Message mesg = new MimeMessage(session);
			InternetAddress[] addresses;

			/** from 地址列表 */
			if (!from.equals("")) {
				
				mesg.setFrom(new InternetAddress(from));
			} else {
				
					System.out.println("请填写发信人地址");
					return -2;
				
			}
			
			/** TO地址列表 */
			if (!to.equals("")) {
				addresses = InternetAddress.parse(to);
				mesg.setRecipients(javax.mail.Message.RecipientType.TO,
						addresses);
			//	mesg.setr
				//mesg.setr
			} else {
				System.out.println("请填写收信人地址");
				return -3;
			}
			/** CC地址列表 抄送*/
			if (cc!=null&&!cc.equals("")) {
				//wlog.userLog(cc);
				addresses = InternetAddress.parse(cc);
				
				mesg.setRecipients(javax.mail.Message.RecipientType.CC,
						addresses);
			}
			/** 设置邮件主题topic */
			if (!subject.equals("")) {
				mesg.setSubject(subject);
			} else {
				mesg.setSubject(subject);
				System.out.println("请填写邮件主题");
			}

			/** 设置邮件内容 */
			if (attchFile==null || attchFile.equals("")) {
				mesg.setContent(body, "text/html;charset=GBK");
				//mesg.setText(body);
			} else {
				Multipart mp = new MimeMultipart();
				MimeBodyPart mbp = new MimeBodyPart();

				mbp.setContent(body, "text/html;charset=GBK");
				mp.addBodyPart(mbp);
				/** 添加附件 */
				ArrayList attachlist = tokenize(attchFile);
				for (int i = 0; i < attachlist.size(); i++) {
					MimeBodyPart attachMbp = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(
							(String) (attachlist.get(i)));
					attachMbp.setDataHandler(new DataHandler(fds));
					attachMbp.setFileName(MimeUtility.encodeText(fds.getName(),
							"GBK", "B"));
					attachMbp.setHeader("Content-Type", fds.getContentType());
					mp.addBodyPart(attachMbp);
				}
				mesg.setContent(mp);
			}
			/** 设置邮件发送时间 */
			mesg.setSentDate(new Date());
			/** 发送邮件 */
			if (authFlag) {
				Transport tr = session.getTransport("smtp");
				tr.connect(sendHost, user, password);
				mesg.saveChanges();
				tr.sendMessage(mesg, mesg.getAllRecipients());
				tr.close();
			} else {
				Transport.send(mesg);
			}
		}catch (MessagingException e) {/* send发送邮件的异常处理 */
			System.out.println("邮件发送失败!");
			successFlag=-9;
			e.printStackTrace();
		} catch (Exception e) {
			successFlag=-9;
			e.printStackTrace();
		}
		return successFlag;
	}
	
	private ArrayList tokenize(String s) {
		ArrayList arrayl = new ArrayList();
		for (StringTokenizer stringtok = new StringTokenizer(s, ","); stringtok
				.hasMoreTokens(); arrayl.add(stringtok.nextToken().trim()))
			;
		return arrayl;
	}
	String sendProtocol = "smtp";
	String receiveProtocol = "pop3";


	/**
	 * 覆盖方法 
	 */
	public boolean sendEmail(String to,String cc, String subject, String body,
			String attchFile) {
		int successflag=sendEmailNow(to,cc,subject,body,attchFile);
		if(successflag==0){
			return true;
		}else{
			return false;
		}
	}

}


配置文件:
emailserver.properties:
emailserver.sendHost=//邮箱服务器,比如163的:smtp.163.com
emailserver.receiveHost=//不填
emailserver.user=//发送邮件的用户名,该邮箱必须是emailserver.sendHost的邮箱
emailserver.password=//发送邮件的密码
emailserver.from=//同emailserver.user
发邮件需要的jar包:
 activation.jar,mail.jar

可能出现的异常:

Exception in thread "main" java.lang.NoClassDefFoundError:

com/sun/mail/util/LineInputStreams

 

原因是jar包版本不统一,解决方法如下:

删除Java EE 5 Libraries/javaee.jar/mail里的包有东西.

具体方法如下:

在Myeclipse6.0.1中用rar打开X:/Program Files/MyEclipse 6.0/

myeclipse/eclipse/plugins/

com.genuitec.eclipse.j2eedt.core_6.0.1.zmyeclipse601200710/

data/libraryset/EE_5/

javaee.jar

在Myeclipse8.5中 D:/Program Files/MyEclipse 8.5/

Common/plugins/

com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033/

data/libraryset/EE_5/EE_5/javaee.jar ,然后删除mail,一切就ok了.

若删除的时候出错,则需要先在myeclipse里面删除掉引用了J2ee5.0的工程,

然后再关闭myeclipse再进行删除操作。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值