现在的位置: 首页 > 综合 > 正文

javamail发送网页邮件,且有中文

2013年01月24日 ⁄ 综合 ⁄ 共 1350字 ⁄ 字号 评论关闭
public void sendMail() throws IOException {
	// create some properties and get the default Session
	Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.sina.com.cn");
	props.setProperty("mail.smtp.auth", "true");   //这个必须加上 否则发送不了
	UserAuthenticator userAuthenticator = new UserAuthenticator("wyxz126@sina.com", "i5v2y6");
	Session session = Session.getInstance(props, userAuthenticator);
	session.setDebug(true);
	try {
	// create a message
	MimeMessage msg = new MimeMessage(session);
	msg.setFrom(new InternetAddress("wyxz126@sina.com"));
	InternetAddress[] address = {new InternetAddress(addressurl)};
	msg.setRecipients(Message.RecipientType.TO, address);
	msg.setSubject("会员注册成功 - ITeye做最棒的软件开发交流社区");
	msg.setSentDate(new Date());
	
	
	DataHandler data = new DataHandler(msgTextBuffer.toString(),"text/html;charset=gb2312"); //这是发送的是网页形式并且有中文
	msg.setDataHandler(data);
	// send the message
	Transport.send(msg);
	
	} catch (MessagingException mex) {
	mex.printStackTrace();
	Exception ex = null;
	if ((ex = mex.getNextException()) != null) {
	ex.printStackTrace();
	}
	}
	}

注意如果发送里面有连接,是邮件里可以直接点击连接而不是单纯的字符,需要写成

DataHandler data = new DataHandler(msgTextBuffer.toString(),"text/html;charset=gb2312");告诉javamail发送的是text/html类型,言外之意

msgTextBuffer.toString()里面要用html标签,而charset=gb2312解决中文乱码

还要注意在写连接的时候要写成<a href='//www.baidu.com'>baidu</a>

如果不加“//”会以邮箱连接相对url比如http://cwebmail.mail.163.com/js/www.baidu.com

而如果写成<a href='http://www.baidu.com'>baidu</a>发送不到收件箱,大家可以试试

抱歉!评论已关闭.