论坛首页 Java企业应用论坛

JMail 示例(无附件发送) 欢迎大家拍砖

浏览 2830 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2010-05-28  
最近在研究的Jmail,现在实现了无附件发送邮件,贴出来大家共享一下,不足之处,欢迎大家拍砖啊!请大家注意在选择j2ee 1.4的工程,如果选择了j2ee1.5的工程,请删除j2ee.jar里面的email文件夹。
  首先这个类是用来验证用户名,密码的。
   package com.qj.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * 用于Jmail返回邮箱账号和密码的校验(在这里被Jmail类所用)
 * 
 * @author 朱志杰
 * 
 */
public class SMTPAuthenticator extends Authenticator {
	private String name = "";
	private String password = "";

	public SMTPAuthenticator(String name, String password) {
		this.name = name;
		this.password = password;
	}

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(name, password);
	}

}
  

这个类是用来发送邮件的,其中main方法中有示例程序
package com.qj.mail;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 用于发送jmail邮件 关联java文件 SMTPAuthenticator.java
 * @author 朱志杰
 *
 */
public class Jmail {
	
	/**
	 * 发送jmail
	 * @param title email标题 
	 * @param content Email内容
	 * @param hostSmtp 发件邮箱 smtp地址 如:smtp.163.com
	 * @param hostAddress 发送邮箱地址 如:myzhijie@163.com
	 * @param hostPwd 发送邮箱密码
	 * @param toAddress 接收邮箱地址 如:myzhijie@qq.com
	 */
	public void sendMail(String title, String content,String hostSmtp,String hostAddress
			,String hostPwd,String toAddress) {
		// String hostSmtp = "smtp.163.com"; // 邮箱smtp
		// String hostAddress = "myzhijie@163.com"; // 发件箱地址
		// String hostPwd = ""; // 发件箱密码
		// String toAddress = "myzhijie@qq.com";// 收件箱地址
		try {
			String mail = content;
			// properties里面包含发送邮件服务器的地址
			Properties mailProps = new Properties();
			mailProps.put("mail.smtp.host", hostSmtp);
			mailProps.put("mail.smtp.auth", "true");
			SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(hostAddress,
					hostPwd);
			Session mailSession = Session.getDefaultInstance(mailProps,
					smtpAuthenticator);
			MimeMessage message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(hostAddress));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					toAddress, false));
			message.setSubject(title);
			// System.out.println("准备发送邮件!!!");
			message.setText(mail);
			Transport.send(message);
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}

	 public static void main(String[] args) {
		 Jmail aa = new Jmail();
		 aa.sendMail("朱志杰标题","朱志杰内容","smtp.163.com","myzhijie@163.com","密码","myzhijie@qq.com");
		 System.out.println("Well Done!");
	}
}



  附件中是这个工程的源码,其中包含两个jar文件。大家可以直接下载附件,导入到MyEclipse,运行就可以了,我用的myeclipse是6.0 的。不足之处欢迎大家拍砖啊!
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics