JavaMail基础案例开发

  Java邮件开发案例

   所需jar包有:mailapi.jar,smtp.jar

一.单独邮件发送案例

 

package com.itRed.javamail;

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

public class Demo1 {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

Properties props=new Properties();
props.setProperty("mail.smtp.auth", "true");//认证
props.setProperty("mail.transport.protocol", "smtp");
Session session=Session.getInstance(props);
session.setDebug(true);

Message msg=new MimeMessage(session);
msg.setText("hello world!");
msg.setFrom(new InternetAddress("it_red@sohu.com"));

Transport transport=session.getTransport();
transport.connect("smtp.sohu.com",25, "it_red", "填写该用户的邮箱密码");
transport.sendMessage(msg,new Address[]{new InternetAddress("it_red@sina.com")});
transport.close();
}

}
View Code

 

 

二.邮件多客户发送

package com.itRed.javamail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Demo2 {

/**
* 邮件多客户发送
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub

//创建Properties
Properties props=new Properties();
props.setProperty("mail.smtp.auth", "true");//认证
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.sohu.com");//服务器主机

Session session=Session.getInstance(props,
new Authenticator() //覆盖父类的方法
{
protected PasswordAuthentication getPasswordAuthentication()
{ 
return new PasswordAuthentication("it_red","用户密码");//返回用户名和密码
}
}
);
session.setDebug(true);
//创建message
Message msg=new MimeMessage(session);
msg.setFrom(new InternetAddress("it_red@sohu.com"));
msg.setSubject("中文主题");
msg.setRecipients(RecipientType.TO,
InternetAddress.parse("it_red@sina.com,it_red@sohu.com"));
msg.setContent("<span style='color:red;'>这是java编写的邮件程序</span>", "text/html;charset=UTF-8");

Transport.send(msg);
}

}
View Code

 

posted on 2014-04-03 20:05  itRed  阅读(527)  评论(0编辑  收藏  举报

导航