java调用163邮箱发送邮件

1:注册一个163邮箱,http://mail.163.com
调用发送邮件代码,查询smtp.163.com,作为发送邮件的服务器ip,类似的邮箱服务器应该也可以。

MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("121.195.178.51");//邮件服务器ip地址。smtp.163.com,
mailInfo.setMailServerPort("25");//端口
mailInfo.setValidate(true);
mailInfo.setUserName("xiongcheng@126.com");//能够登录126的邮箱
mailInfo.setPassword("*****");//密码
mailInfo.setFromAddress("****@163.com");//显示发送发邮箱地址
mailInfo.setToAddress("****@126.com");//接收邮件地址
mailInfo.setSubject("标题");
mailInfo.setContent("发送内容");// 这个类主要来发送邮件
SimpleMailSender sms = new SimpleMailSender();// 发送html格式
return sms.sendHtmlMail(mailInfo);

邮件发送方法

/**
 * 以HTML格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件信息
 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {

	Properties pro = mailInfo.getProperties();

	Session sendMailSession = Session.getInstance(pro);
	try {
		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(mailInfo.getFromAddress());
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址,并设置到邮件消息中
		Address to = new InternetAddress(mailInfo.getToAddress());
		// Message.RecipientType.TO属性表示接收者的类型为TO
		mailMessage.setRecipient(Message.RecipientType.TO, to);
		// 设置邮件消息的主题
		mailMessage.setSubject(mailInfo.getSubject());
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		// 设置HTML内容
		html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage);
		return true;
	} catch (MessagingException ex) {
		if (ex.getCause() instanceof SendFailedException) {
			//发送失败, 更新发送状态为1.
			return false;
		}
		ex.printStackTrace();
	}
	return false;
}



原文地址:https://www.cnblogs.com/snake-hand/p/3153406.html