欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaMail发送html格式的邮件

程序员文章站 2022-07-14 21:13:11
...

  之前分享过一个发邮件的类,今天再分享一个收邮件的类,

 

package zhang.stony.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
/**
 * @author Stony Zhang  (Mybeautiful)
 * @Createdate 2010-8-12
 * @Emal:stonyz@live.com
 * @QQ:55279427
 */
public class MailSender {
	private MailSetting mSetting;

	private Session session;

	public MailSender(MailSetting mSetting) {
		this.mSetting = mSetting;

		final String username = mSetting.getUser();
		final String password = mSetting.getPassword();
		Properties props = new Properties();
		props.put("mail.smtp.host", mSetting.getSmtpHost());
		props.put("mail.smtp.auth", "true");
		session = Session.getInstance(props, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});
	}

	public void sentMessage(String titile, String msg, String[] to)
			throws MessagingException {
		this.sentMessage(titile, msg, to, null);
	}

	public void sentMessage(String titile, String msg, String[] to, String[] cc)
			throws MessagingException {
		Message mailMessage = new MimeMessage(session);
		Address from = new InternetAddress(mSetting.getUser());
		mailMessage.setFrom(from);
		// Address to = new InternetAddress(mSetting.getUser());

		Address[] tos = new Address[to.length];
		for (int i = 0; i < to.length; i++) {
			tos[i] = new InternetAddress(to[i]);
		}
		mailMessage.setRecipients(Message.RecipientType.TO, tos);

		if (cc != null && cc.length > 0) {
			Address[] ccs = new Address[cc.length];
			for (int i = 0; i < cc.length; i++) {
				ccs[i] = new InternetAddress(cc[i]);
			}
			mailMessage.setRecipients(Message.RecipientType.CC, ccs);
		}

		mailMessage.setSubject(titile);
		mailMessage.setSentDate(new Date());
//		mailMessage.setText(msg);
		
		   BodyPart mdp = new MimeBodyPart(); 
		    mdp.setContent(msg, "text/html;charset=gb2312"); 
		    Multipart mm = new MimeMultipart(); 
		    mm.addBodyPart(mdp); 
		    mailMessage.setContent(mm); 
		    mailMessage.saveChanges(); 
		
		
		Transport.send(mailMessage);
	}
}

 

 

     其中用到了一个MailSetting的类,其内容请参阅   分享一个收邮件的类,使用相当简单

 

     关于Javamail,几年间已经用了N多次了,其间也碰到了一些问题,也都一一解决了,比如发送附件,乱码等等,如果各位有兴趣就相关问题进行探讨,欢迎留言。 

 

相关标签: HTML QQ