SendMail发邮件

java发送邮件:

 

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


 

 

Map basicMailInfo;

				basicMailInfo = (Map) crudDAO.queryForObject(
						"search.send.mail.info", null);

			// 服务器地址
			String smtpHost = basicMailInfo.get("ATTRIBUTE1").toString();
			// 端口
			String smtpPost = basicMailInfo.get("ATTRIBUTE2").toString();

			// 缺省发件人
			String defaultFrom = basicMailInfo.get("ATTRIBUTE3").toString();
			
			if (StringUtils.isEmpty(mail.getFrom())){
				mail.setFrom(defaultFrom);
			}

			Properties props = new Properties();
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", smtpHost); // 邮件服务器地址
			props.put("mail.smtp.port", smtpPost); // 端口

			Session mailSession = Session.getDefaultInstance(props);

			MimeMessage msg = new MimeMessage(mailSession);

			// 发件人
			msg.addFrom(InternetAddress.parse(mail.getFrom()));

			// 收件人邮箱
			InternetAddress[] addresses = parseAddresses(mail.getTo());

			msg.setRecipients(Message.RecipientType.TO, addresses);

			// 抄送人邮箱
			addresses = parseAddresses(mail.getCc());
			if (addresses.length > 0) {
				msg.setRecipients(Message.RecipientType.CC, addresses);
			}

			// 暗送人邮箱
			addresses = parseAddresses(mail.getBcc());
			if (addresses.length > 0) {
				msg.setRecipients(Message.RecipientType.BCC, addresses);
			}

			// 发送时间
			if (msg.getSentDate() == null) {
				msg.setSentDate(new Date());
			}
			
			String encoding = "GBK";

			// 主题
			msg.setSubject(mail.getSubject(), encoding);

			// 内容
			//msg.setText(mail.getText(), encoding);
			msg.setContent(mail.getText(),"text/html; charset="+encoding) ;
			Transport.send(msg);


 

 

 

你可能感兴趣的:(SendMail发邮件)