package pg.system;
/**
* @author pdw
*
* TODO 发送邮件!
*
*/
import java.util. * ;
import javax.mail. * ;
import javax.mail.internet. * ;
import javax.activation. * ;
import java.security.spec.X509EncodedKeySpec;
public class SendMail {
public MimeMessage mimeMsg; // 要发送的email信息
private Session session;
private Properties props;
private boolean needAuth = false ;
private String username = "" ;
private String password = "" ;
private Multipart mp; // 存放邮件的title 内容和附件
public SendMail(String stmp){
setSmtpHost(stmp);
createMimeMessage();
}
/**
*
* @param hostName
*/
public void setSmtpHost(String hostName){
System.out.println( " mail.stmp.host= " + hostName);
if (props == null ){
props = System.getProperties();
}
props.put( " mail.smtp.host " ,hostName);
}
public boolean createMimeMessage(){
try {
System.out.println( " Session begin----------- " );
session = Session.getInstance(props, null );
} catch (Exception e){
System.out.println( " Session.getInstance faild! " + e);
return false ;
}
System.out.println( " MimeMEssage begin---------! " );
try {
mimeMsg = new MimeMessage(session);
mp = new MimeMultipart();
return true ;
} catch (Exception e){
System.out.println( " MimeMessage fiald! " + e.toString());
return false ;
}
}
/**
*
* @param need
*/
public void setNeedAuth( boolean need){
System.out.println( " :mail.smtp.auth= " + need);
if (props == null ){
props = System.getProperties();
}
if (need){
props.put( " mail.smtp.auth " , " true " );
}
else {
props.put( " mail.smtp.auth " , " false " );
}
}
/**
*
* @param name
* @param pass
*/
public void setNamePass(String name,String pass){
username = name;
password = pass;
}
/**
*
* @param mailSubject
* @return boolean
*/
public boolean setSubject(String mailSubject){
System.out.println( " set title begin


try {
if ( ! mailSubject.equals( "" ) && mailSubject != null ){
mimeMsg.setSubject(mailSubject);
}
return true ;
} catch (Exception e){
System.out.println( " set Title faild! " );
return false ;
}
}
/**
* 添加附件

* @param filename
* @return
*/
public boolean addFileAffix(String filename){
System.out.println( " 增加附件

if (filename.equals( "" ) || filename == null ){
return false ;
}
String file[];
file = filename.split( " ; " );
System.out.println( " 你有 " + file.length + " 个附件! " );
try {
for ( int i = 0 ;i < file.length;i ++ ){
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(file[i]);
bp.setDataHandler( new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
}
return true ;
} catch (Exception e){
System.err.println( " 增加附件: " + filename + " --faild! " + e);
return false ;
}
}
/**
*
* @param from
* @return
*/
public boolean setFrom(String from){
System.out.println( " Set From

try {
mimeMsg.setFrom( new InternetAddress(from));
return true ;
} catch (Exception e){
return false ;
}
}
/**
*
* @param to
* @return
*/
public boolean setTo(String to){
System.out.println( " Set to

if (to == null || to.equals( "" )){
return false ;
}
try {
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true ;
} catch (Exception e){
return false ;
}
}
public boolean setCopyTo(String copyto){
if (copyto.equals( "" ) || copyto == null ){
return false ;
}
try {
String copy[];
copy = copyto.split( " ; " );
for ( int i = 0 ;i < copy.length;i ++ ){
mimeMsg.setRecipients(Message.RecipientType.TO,(Address[])InternetAddress.parse(copy[i]));
}
return true ;
} catch (Exception e){
return false ;
}
}
/**
* 设置信的内容!
* @param mailBody
* @return boolean
*/
public boolean setBody(String mailBody){
try {
BodyPart bp = new MimeBodyPart();
bp.setContent( " <meta http-equiv=Context-Type context=text/html;charset=gb2312> " + mailBody, " text/html;charset=GB2312 " );
mp.addBodyPart(bp);
return true ;
} catch (Exception e){
System.out.println( " Set context Faild! " + e);
return false ;
}
}
/**
*
* @param htmlpath
* @return boolean
*/
public boolean setHtml(String htmlpath){
try {
if ( ! htmlpath.equals( "" ) || htmlpath != null ){
BodyPart mbp = new MimeBodyPart();
DataSource ds = new FileDataSource(htmlpath);
mbp.setDataHandler( new DataHandler(ds));
mbp.setHeader( " Context-ID " , " meme " );
mp.addBodyPart(mbp);
}
return true ;
} catch (Exception e){
System.err.println( " Set Html Faild! " + e);
return false ;
}
}
public boolean setOut(){
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println( " 正在SendMail

Session mailSession = session.getInstance(props, null );
Transport tp = mailSession.getTransport( " smtp " );
tp.connect((String)props.getProperty( " mail.stmp.host " ),username,password);
tp.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
// tp.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
System.out.println( " Send Mail 成功.. " );
tp.close();
return true ;
} catch (Exception e){
e.printStackTrace();
return false ;
}
}
}
测试类]
package pg.system;
public class SendMailDemo {
public static void main(String[] args) {
SendMail sm = new SendMail( " mail.ldtec.com " );
sm.setNamePass( " peidewan@ldtec.com " , " 123456 " );
sm.setSubject( " 测试,测试




sm.setFrom( " peidewan@ldtec.com " );
sm.setTo( " pdw2009@yahoo.com.cn " );
sm.addFileAffix( " f:/adsl.txt " );
StringBuffer bs = new StringBuffer();
bs.append( " 裴德万:/n " );
bs.append( " 测试度奇珍异宝埼地在檌!!!!!!!!!!! " );
sm.setBody( " DFSAAAAAAAAAAAAAAAAA " );
sm.setNeedAuth( true );
boolean b = sm.setOut();
if (b){
System.out.println( " /n邮件发送成功!!!!! " );
}
else {
System.out.println( " 邮件发送失败!!!! " );
}
}
}
很久以前写的一个发邮件的例,今天把它贴出来做笔记!!
gmail邮件收发。
package
test;
import java.security.Security;
import java.util. * ;
import javax.mail. * ;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 定时收取新邮件类
* @author peidw
*
*/
class ReceiveNewMailTimerTask extends TimerTask{
static Store store = null ;
static String username = " pdw2009@gmail.com " ;
static String password = " pdw123456 " ;
/**
* 静态初始化模块,只保留一个Store连接
*/
static {
try {
connect(username,password);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 任务计划执行方法
*/
@Override
public void run() {
try {
System.out.println( " 正在读取邮箱
.
"
);
printNewMailInfo(getNewMessage(username,password));
} catch (Exception e){
e.printStackTrace();
}
}
private static void connect(String username,String password) throws Exception{
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = " javax.net.ssl.SSLSocketFactory " ;
Properties props = System.getProperties();
props.setProperty( " mail.pop3.socketFactory.class " , SSL_FACTORY);
props.setProperty( " mail.pop3.socketFactory.fallback " , " false " );
props.setProperty( " mail.pop3.port " , " 995 " );
props.setProperty( " mail.pop3.socketFactory.port " , " 995 " );
Session session = Session.getDefaultInstance(props, null );
URLName urln = new URLName( " pop3 " , " pop.gmail.com " , 995 , null ,
username, password);
store = session.getStore(urln);
store.connect();
}
/**
* 读取新邮件
* @param username
* @param password
* @return
* @throws Exception
*/
public Message[] getNewMessage(String username,String password) throws Exception{
if (store.isConnected()){
connect(username,password);
}
Folder inbox = store.getFolder( " INBOX " );
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
if (inbox.getUnreadMessageCount() > 0 ){
int fetchcount = inbox.getMessageCount() - inbox.getUnreadMessageCount();
if (fetchcount == 0 ) return inbox.getMessages();
Message[] mesg = inbox.getMessages( 1 , 2 ); // 取取未读邮件
return mesg;
} else {
System.out.println( " 不存在新邮件.. " );
throw new RuntimeException( " 不存在新邮件 " );
}
}
/**
* 打印邮件信息
* @param message
* @throws Excepiton
*/
public void printNewMailInfo(Message[] message) throws Exception{
Message msg = null ;
String text = null ;
for ( int i = 0 ;i < message.length;i ++ ){
msg = message[i];
text = msg.getSubject();
if (text == null ){
System.out.println( " 该邮件没标准 " );
} else if (text.startsWith( " =GBK " ) || text.startsWith( " =gb2312 " )){
text = MimeUtility.decodeText(text);
} else {
text = new String(text.getBytes( " gb2312 " ));
}
System.out.println( " -- " + text);
}
}
}
public class GmailReceiveAndSend {
public void sendMail() throws Exception{
// 收邮件的连接
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = " javax.net.ssl.SSLSocketFactory " ;
Properties props = System.getProperties();
props.setProperty( " mail.smtp.host " , " smtp.gmail.com " );
props.setProperty( " mail.smtp.socketFactory.class " , SSL_FACTORY);
props.setProperty( " mail.smtp.socketFactory.fallback " , " false " );
props.setProperty( " mail.smtp.port " , " 465 " );
props.setProperty( " mail.smtp.socketFactory.port " , " 465 " );
props.put( " mail.smtp.auth " , " true " );
final String username = " pdw2009 " ;
final String password = " pdw123456 " ;
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password );
}});
Message msg = new MimeMessage(session);
msg.setFrom( new InternetAddress( " pdw2009 " + " @gmail.com " ));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse( " pdw2009@qq.com " , false ));
msg.setSubject( " 你好 " );
msg.setText( " gmail 邮件测试 " );
msg.setSentDate( new Date());
Transport.send(msg);
System.out.println( " Message sent. " );
}
public static void main(String[] args) throws Exception{
ReceiveNewMailTimerTask task = new ReceiveNewMailTimerTask();
Timer timer = new Timer();
// timer.schedule(task,2000,1*60*1000);
GmailReceiveAndSend gs = new GmailReceiveAndSend();
gs.sendMail();
}
}
import java.security.Security;
import java.util. * ;
import javax.mail. * ;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 定时收取新邮件类
* @author peidw
*
*/
class ReceiveNewMailTimerTask extends TimerTask{
static Store store = null ;
static String username = " pdw2009@gmail.com " ;
static String password = " pdw123456 " ;
/**
* 静态初始化模块,只保留一个Store连接
*/
static {
try {
connect(username,password);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 任务计划执行方法
*/
@Override
public void run() {
try {
System.out.println( " 正在读取邮箱

printNewMailInfo(getNewMessage(username,password));
} catch (Exception e){
e.printStackTrace();
}
}
private static void connect(String username,String password) throws Exception{
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = " javax.net.ssl.SSLSocketFactory " ;
Properties props = System.getProperties();
props.setProperty( " mail.pop3.socketFactory.class " , SSL_FACTORY);
props.setProperty( " mail.pop3.socketFactory.fallback " , " false " );
props.setProperty( " mail.pop3.port " , " 995 " );
props.setProperty( " mail.pop3.socketFactory.port " , " 995 " );
Session session = Session.getDefaultInstance(props, null );
URLName urln = new URLName( " pop3 " , " pop.gmail.com " , 995 , null ,
username, password);
store = session.getStore(urln);
store.connect();
}
/**
* 读取新邮件
* @param username
* @param password
* @return
* @throws Exception
*/
public Message[] getNewMessage(String username,String password) throws Exception{
if (store.isConnected()){
connect(username,password);
}
Folder inbox = store.getFolder( " INBOX " );
inbox.open(Folder.READ_ONLY);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
if (inbox.getUnreadMessageCount() > 0 ){
int fetchcount = inbox.getMessageCount() - inbox.getUnreadMessageCount();
if (fetchcount == 0 ) return inbox.getMessages();
Message[] mesg = inbox.getMessages( 1 , 2 ); // 取取未读邮件
return mesg;
} else {
System.out.println( " 不存在新邮件.. " );
throw new RuntimeException( " 不存在新邮件 " );
}
}
/**
* 打印邮件信息
* @param message
* @throws Excepiton
*/
public void printNewMailInfo(Message[] message) throws Exception{
Message msg = null ;
String text = null ;
for ( int i = 0 ;i < message.length;i ++ ){
msg = message[i];
text = msg.getSubject();
if (text == null ){
System.out.println( " 该邮件没标准 " );
} else if (text.startsWith( " =GBK " ) || text.startsWith( " =gb2312 " )){
text = MimeUtility.decodeText(text);
} else {
text = new String(text.getBytes( " gb2312 " ));
}
System.out.println( " -- " + text);
}
}
}
public class GmailReceiveAndSend {
public void sendMail() throws Exception{
// 收邮件的连接
Security.addProvider( new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = " javax.net.ssl.SSLSocketFactory " ;
Properties props = System.getProperties();
props.setProperty( " mail.smtp.host " , " smtp.gmail.com " );
props.setProperty( " mail.smtp.socketFactory.class " , SSL_FACTORY);
props.setProperty( " mail.smtp.socketFactory.fallback " , " false " );
props.setProperty( " mail.smtp.port " , " 465 " );
props.setProperty( " mail.smtp.socketFactory.port " , " 465 " );
props.put( " mail.smtp.auth " , " true " );
final String username = " pdw2009 " ;
final String password = " pdw123456 " ;
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password );
}});
Message msg = new MimeMessage(session);
msg.setFrom( new InternetAddress( " pdw2009 " + " @gmail.com " ));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse( " pdw2009@qq.com " , false ));
msg.setSubject( " 你好 " );
msg.setText( " gmail 邮件测试 " );
msg.setSentDate( new Date());
Transport.send(msg);
System.out.println( " Message sent. " );
}
public static void main(String[] args) throws Exception{
ReceiveNewMailTimerTask task = new ReceiveNewMailTimerTask();
Timer timer = new Timer();
// timer.schedule(task,2000,1*60*1000);
GmailReceiveAndSend gs = new GmailReceiveAndSend();
gs.sendMail();
}
}