java邮箱代码_java邮箱开发代码——发邮件

public class Demo1 {

/**

* @param args

* @throws MessagingException

*/

public static void main(String[] args) throws MessagingException {

//第一种方式方式

//send1();

//第二种发送方式

send2();

}

public static void send1()

{

try {

/**

构建发送环境

*/

Properties properties = new Properties();

properties.setProperty("mail.smtp.auth", "true");//接受认证

properties.setProperty("mail.transport.protocol", "smtp");//设置发送协议

Session session =Session.getDefaultInstance(properties);

session.setDebug(true);//设置在控制台打印调试信息

/**

* 构建邮件

*/

Message msg = new MimeMessage(session);

msg.setText("逗你玩");//发送内容

msg.setFrom(new InternetAddress("xxxx@qq.com"));//设置发送邮件方地址

/*

构建发送类

*/

Transport transport = session.getTransport();

transport.connect("smtp.qq.com", 25, "xxxxxx用户名", "zxxxx密码");//设置要连接的服务器地址、端口、用户名、密码

transport.sendMessage(msg, new InternetAddress[]{new InternetAddress("13628303286@163.com")});//发送邮件给某些人

transport.close();//关闭发送链接

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static void send2() throws AddressException, MessagingException

{

/**

构建发送环境

*/

Properties properties = new Properties();

properties.setProperty("mail.smtp.auth", "true");//接受服务器认证

properties.setProperty("mail.transport.protocol", "smtp");//设置发送协议

properties.setProperty("mail.host", "smtp.qq.com");//设置要连接的服务器地址,端口默认25

Session session = Session.getInstance(properties,new Authenticator() { //策略模式

@Override

protected PasswordAuthentication getPasswordAuthentication() { //返回用户名和密码

// TODO Auto-generated method stub

return new PasswordAuthentication("xxxx用户名", "xxxxxxx密码"); //设置用户名和密码

}

});

session.setDebug(true); //显示调试信息

/**

* 构建邮件

*/

Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress("594389@qq.com"));//设置发送方地址

msg.setSubject("中文主题");

msg.setRecipients(RecipientType.TO, InternetAddress.parse("2399548@qq.com,13628303286@163.com,594389@qq.com")); //设置收件人的类型:TO:收件人;CC:抄送;BCC:暗送;和收件人

msg.setContent("中文呵呵", "text/html;charset=gbk");//设置发送内容,以及内容的类型和编码

/**

* 发送邮件

*/

Transport.send(msg);

}

}

注:工程需要引入mail.jar包,如果运行环境低于jdk6还需引入activation.jar包

下载地址:http://download.csdn.net/user/zl594389970

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值