邮件原理与JavaMail开发 (二)

2014-11-24 10:09:13 · 作者: · 浏览: 1
与邮件服务器建立网络连接的会话信息,如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。Session对象根据这些信息构建用于邮件收发的Transport和Store对象,以及为客户端创建Message对象时提供信息支持。


13、邮件发送程序


使用JavaMail发送一封简单的邮件:

创建包含邮件服务器的网络连接信息的Session对象。

创建代表邮件内容的Message对象。

创建Transport对象、连接服务器、发送Message、关闭连接。


==============JavaMail发送简单邮件-=====================


@Test

public void test1() throws Exception, MessagingException{

Properties prop = new Properties();

prop.setProperty("mail.transport.protocol", "smtp");

prop.setProperty("mail.smtp.host", "localhost");

// prop.setProperty("mail.smtp.auth", "true");

prop.setProperty("mail.debug", "true");

Session session = Session.getInstance(prop);


Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress("aa@park.cn"));

msg.setRecipient(RecipientType.TO, new InternetAddress("bb@park.cn"));

msg.setSubject("来自javaMail的测试邮件!");

msg.setText("来自javaMail的正文内容。。");


Transport tran = session.getTransport();

tran.connect("aa", "123");

tran.send(msg, msg.getAllRecipients());

}


=========================================================

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

Properties prop = new Properties();

prop.setProperty("mail.transport.protocol", "smtp");

prop.setProperty("mail.smtp.host", "smtp.sina.cn");

prop.setProperty("mail.smtp.auth", "true");

prop.setProperty("mail.debug", "true");


Session session = Session.getInstance(prop);

Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress("itheima_park@sina.cn"));

msg.setRecipient(RecipientType.TO, new InternetAddress("itheima_park@sohu.com"));

msg.setSubject("这是我写的标题XXXXXXXXXX");

msg.setText("这是邮件的正文");