java 利用mail.jar发送邮件

JavaMail是什么:

JavaMail是SUN提供给开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发类库,支持常用的邮件协议,如SMTP、POP3、IMAP,开发人员使用JavaMail编写邮件程序时,无需考虑底层的通信细节(Socket),JavaMail也提供了能够创建出各种复杂MIME格式的邮件内容的API。使用JavaMail,我们可以实现类似OutLook、FoxMail的软件。虽然JavaMail(仅支持JDK4及以上)也是Java的API之一,但是却没有直接加入到JDK中,所以我们需要另行下载。另外,JavaMail依赖JAF(JavaBeans Activation Framework),JAF在Java6之后已经合并到JDK中,而JDK5之前需要另外下载JAF的类库。

JavaMail发送邮件:

首先下载javamail所需的jar包 点击下载mail

下面开始撸代码了:

使用163邮箱服务器给qq邮箱发送邮件

package com.yrok.email;

import java.util.Properties;

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.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class Email2 {

	/**
	 * 使用Transport 非静态方法 发送邮件 连接163服务,给QQ邮箱发邮件
	 */
	public static void main(String[] args) throws Exception {
		// 属性对象
		Properties properties = new Properties();
		// 开启debug调试 ,打印信息
		properties.setProperty("mail.debug", "true");
		// 发送服务器需要身份验证
		properties.setProperty("mail.smtp.auth", "true");
		// 发送服务器端口,可以不设置,默认是25
		properties.setProperty("mail.smtp.port", "25");
		// 发送邮件协议名称
		properties.setProperty("mail.transport.protocol", "smtp");
		// 设置邮件服务器主机名
		properties.setProperty("mail.host", "smtp.163.com");
		// 环境信息
		Session session = Session.getInstance(properties, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 在session中设置账户信息,Transport发送邮件时会使用
				return new PasswordAuthentication("username@163.com", "password");
			}
		});

		// 创建邮件对象
		Message message = new MimeMessage(session);
		// 设置主题
		message.setSubject("Tets email");
		// 发件人
		message.setFrom(new InternetAddress("username@163.com"));
		// 多个收件人
		message.setRecipients(RecipientType.TO, InternetAddress.parse("reciveUser@qq.com"));
		// 抄送人
		message.setRecipient(RecipientType.CC, new InternetAddress("reciveuser1@qq.com"));
		// 暗送人
		message.setRecipient(RecipientType.BCC, new InternetAddress("reciveuser2@qq.com"));
		// HTML内容
		message.setContent("<a href='http://blog.csdn.net/y534560449'>Hello Boy!!</a>", "text/html;charset=utf-8");

		// 连接邮件服务器、发送邮件、关闭连接,全做了
		Transport.send(message);

	}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值