利用JAVAMAIL发送邮件

不知道该叫原创还是叫转贴.有参考别人代码,也有自己的创新.如有版权问题请及时通知我.

1. 一个单例的发送类

package sendmail;


import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
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 javax.mail.internet.MimeUtility;

/**
 * <p> Title: MailSender</p>
 * <p> Description:</p>
 * <p>Created: 2011-4-14 下午08:49:13</p>
 * 
 * @author ShengYan
 * @version
 */
public class MailSender {
	static {
		getProperties();
	}
	
    private MailSender() {
    }

    static class SingletonHolder {
        static MailSender instance = new MailSender();
    }

    public static MailSender getInstance() {
        return SingletonHolder.instance;
    }
	
	private static String HOST;
	private static String USERNAME;
	private static String PASSWORD;
	private static String FROM;
	private static String TO;
	private static String MAIL_HOST="smtp.mobiscloud.com";
	private static String MAIL_USERNAME="support@mobiscloud.com";
	private static String MAIL_PASSWORD="1123456";
	private static String MAIL_FROM="support@mobiscloud.com";
	private static String MAIL_TO="sheng.yan@mobiscloud.com";
	public static final String EMAIL_SUBJECT = "subject";
	public static final String EMAIL_TEXT = "text";
	public static final String EMAIL_ATTACHMENT = "attachment";

	public static void main(String[] args) {
		MailSender sender = MailSender.getInstance();
		Map<String, String> map = new HashMap<String, String>();
		map.put(EMAIL_SUBJECT, "标题 is xxx");
		map.put(EMAIL_TEXT, "内容 is ccc");
		map.put(EMAIL_ATTACHMENT,
				"C:/Users/yansheng/Pictures/binding_expression.png");
		sender.sendEmail(map);
	}
	
	private static void getProperties() {
		String path = MailSender.class.getResource(MailSender.class.getSimpleName() + ".properties").getPath();
		path = path.substring(1);
		System.out.println("-------------mailsender path: " + path);
		Properties prop = new Properties();
		FileReader reader = null;
		try {
			reader = new FileReader(path);
			prop.load(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (null != reader) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (0 != prop.size()) {
			HOST = prop.getProperty("MAIL_HOST");
			USERNAME = prop.getProperty("MAIL_USERNAME");
			PASSWORD = prop.getProperty("MAIL_PASSWORD");
			FROM = prop.getProperty("MAIL_FROM");
			TO = prop.getProperty("MAIL_TO");
		} else {
			HOST = MAIL_HOST;
			USERNAME = MAIL_USERNAME;
			PASSWORD = MAIL_PASSWORD;
			FROM = MAIL_FROM;
			TO = MAIL_TO;
		}
	}
	

	public boolean sendEmail(Map<String, String> data) {
		// 创建Properties 对象
		Properties props = System.getProperties();
		props.put("mail.smtp.host", HOST); // 全局变量
		props.put("mail.smtp.auth", "true");

		// 创建邮件会话
		//不带auth
//		Session session = Session.getDefaultInstance(props);
		Session session = Session.getDefaultInstance(props,
				new Authenticator() { // 验账账户
					@Override
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(USERNAME, PASSWORD);
					}
				});

		try {
			// 定义邮件信息
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(FROM));
			message.addRecipients(Message.RecipientType.TO, TO);
			// 添加邮件发送时间(不知道体现在哪儿)
			message.setSentDate(new Date());
			// 要编码,否则中文会出乱码,貌似这个方法是对数据进行了
			// ("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=")形势的包装
			message.setSubject(MimeUtility.encodeText(data.get(EMAIL_SUBJECT),
					"gbk", "B"));

			MimeMultipart mmp = new MimeMultipart();
			MimeBodyPart mbp_text = new MimeBodyPart();
			// "text/plain"是文本型,没有样式,
			// "text/html"是html样式,可以解析html标签
			mbp_text.setContent(data.get(EMAIL_TEXT), "text/html;charset=gbk");
			mmp.addBodyPart(mbp_text); // 加入邮件正文

			// 处理附件,可以添加多个附件
			if (data.get(EMAIL_ATTACHMENT) != null) {
				String[] files = data.get(EMAIL_ATTACHMENT).split(",");
				if (files.length != 0) {
					for (String file : files) {
						MimeBodyPart mbp_file = new MimeBodyPart();
						FileDataSource fds = new FileDataSource(file);
						mbp_file.setDataHandler(new DataHandler(fds));
						mbp_file.setFileName(MimeUtility.encodeText(
								fds.getName(), "gbk", "B"));
						mmp.addBodyPart(mbp_file);
					}
				}
			}
			message.setContent(mmp);
			// message.setText(data.get(Constants.EMAIL_TEXT));

			// 发送消息
			// session.getTransport("smtp").send(message); //也可以这样创建Transport对象
			Transport.send(message);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}

2.一个properties文件

#POST 服务器MAIL_HOST=g.gmail.com
#发件登录用户MAIL_USERNAME=support@google.com
#发件登录密码MAIL_PASSWORD=1123456
#发件人MAIL_FROM=support@google.co
m#收件人MAIL_TO=recevie@google.com

参考资料:http://coolshell.cn/articles/4261.html

参与评论 您还未登录,请先 登录 后发表或查看评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值