利用javax.mail发送邮件

来源:互联网 发布:开源cms系统 编辑:程序博客网 时间:2024/05/02 01:05

自己无聊参考网上的资料自己做一个简单的发送案例;

具体程序如下:


package mail;

import java.util.Properties;

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

//JavaMail 发送邮件
public class JavaEmail {


public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
properties.setProperty("mail.smtp.auth", "true");//需要验证
properties.setProperty("mail.debug", "true");//设置debug模式 后台输出邮件发送的过程
Session session = Session.getInstance(properties);
session.setDebug(true);//debug模式
//邮件信息
Message messgae = new MimeMessage(session);
messgae.setFrom(new InternetAddress("xiexingxingvip@sina.com"));//设置发送人
messgae.setText("what's up man");//设置邮件内容
messgae.setSubject("哥们该吃饭了");//设置邮件主题
//发送邮件
Transport tran = session.getTransport();

tran.connect("smtp.sina.com", 25, "xiexingxingvip@sina.com", "********");//连接到新浪邮箱服务器

tran.sendMessage(messgae, new Address[]{ new InternetAddress("1359407730@qq.com")});//设置邮件接收人
tran.close();
}
}


上述例子是利用新浪邮箱往QQ邮箱发送测试邮件。发送邮件的邮箱需设置smtp协议开启,不然程序报错无法发送邮件。

0 0