JavaMail实现SMTP客户端,由发送端服务器转发。

//Modified by zealvampire 07-4-4,排版

    JavaMail这个封装用起来也算方便,但如果是做界面的时候会发觉发送的时候你比较难跟踪它的过程,是在登陆验证密码还是正在发送;虽然可以设置session.setDebug(true)并且把输出流导向到UI界面,但是新版本的封装会把附件所有内容都打出来。。。建议要加点回调函数。

import java.io.File;
import java.io.PrintStream;
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.*;

public class sendMails
    
implements TransportListener
{

    
public sendMails()
    
{
        authFlag 
= false;
        mimeType 
= "text/html";
        accessories 
= new ArrayList();
    }


    
public void setUser(String user)
    
{
        
this.user = user;
    }


    
public void setPassword(String password)
    
{
        
this.password = password;
    }


    
public void setFromAddress(String fromAddress)
    
{
        
this.fromAddress = fromAddress;
    }


    
public void setSmtpServerDns(String smtpServerDns)
    
{
        
this.smtpServerDns = smtpServerDns;
    }


    
public void setAuthFlag(boolean authFlag)
    
{
        
this.authFlag = authFlag;
    }


    
public void setReceiver(String receiver[])
    
{
        
this.receiver = receiver;
    }


    
public void setTitle(String title)
    
{
        
this.title = title;
    }


    
public void setContent(String content)
    
{
        
this.content = content;
    }


    
public void setAccessories(ArrayList accessories)
    
{
        
this.accessories = accessories;
    }


    
public void setMimeType(String mimeType)
    
{
        
this.mimeType = mimeType;
    }


    
public void initSession()
    
{
        Properties p 
= new Properties();
        p.put(
"mail.host", smtpServerDns);
        p.put(
"mail.smtp.auth", String.valueOf(authFlag));
        MailAuthenticator author 
= new MailAuthenticator(user, password);
        session 
= Session.getInstance(p, author);
        session.setDebug(
true);
    }


    
public void initMimeMessage()
    
{
        
if(session == null)
            initSession();
        mimeMesg 
= new MimeMessage(session);
        
try
        
{
            mimeMesg.setFrom(
new InternetAddress(fromAddress));
            InternetAddress toAddress[] 
= new InternetAddress[receiver.length];
            
for(int i = 0; i < receiver.length; i++)
                toAddress[i] 
= new InternetAddress(receiver[i]);

            mimeMesg.addRecipients(javax.mail.Message.RecipientType.TO, toAddress);
            mimeMesg.setSubject(title);
        }

        
catch(MessagingException e)
        
{
            e.printStackTrace();
        }

    }


    
public void formMimeMessage()
    
{
        
if(mimeMesg == null)
            initMimeMessage();
        MimeMultipart mimeMultipart 
= new MimeMultipart();
        BodyPart contentBodyPart 
= new MimeBodyPart();
        StringBuffer contentBuf 
= new StringBuffer("<meta content=text/html; charset=gb2312>");
        contentBuf.append(content);
        
try
        
{
            contentBodyPart.setContent(contentBuf.toString(), 
"text/html;charset=GB2312");
            mimeMultipart.addBodyPart(contentBodyPart);
            
if(!accessories.isEmpty())
            
{
                MimeBodyPart fileBodyPart;
                
for(Iterator it = accessories.iterator(); it.hasNext(); mimeMultipart.addBodyPart(fileBodyPart))
                
{
                    String filePath 
= (String)it.next();
                    fileBodyPart 
= new MimeBodyPart();
                    FileDataSource fileDataSource 
= new FileDataSource(filePath);
                    fileBodyPart.setDataHandler(
new DataHandler(fileDataSource));
                    fileBodyPart.setFileName(MimeUtility.encodeWord(fileDataSource.getName(), 
"GB2312"null));
                }


            }

            mimeMesg.setContent(mimeMultipart);
            mimeMesg.saveChanges();
            mimeMesg.setSentDate(
new Date());
        }

        
catch(MessagingException e)
        
{
            e.printStackTrace();
        }

        
catch(Exception ex)
        
{
            ex.printStackTrace();
        }

    }


    
public void send()
    
{
        
if(mimeMesg == null)
            formMimeMessage();
        
try
        
{
            Transport.send(mimeMesg);
            
if(accessories != null && accessories.size() != 0)
            
{
                
for(int i = 0; i < accessories.size(); i++)
                
{
                    File f 
= new File(accessories.get(i).toString());
                    f.delete();
                }


                accessories.clear();
            }

        }

        
catch(Exception e)
        
{
            e.printStackTrace();
        }

    }


    
public void messageDelivered(TransportEvent event)
    
{
        Address add[] 
= event.getValidSentAddresses();
        printEvent(event, add);
        System.out.println(
"以上地址成功发送.");
    }


    
public void messageNotDelivered(TransportEvent event)
    
{
        Address add[] 
= event.getValidUnsentAddresses();
        printEvent(event, add);
        System.out.println(
"以上合法地址未能发送.");
    }


    
public void messagePartiallyDelivered(TransportEvent event)
    
{
        Address add[] 
= event.getValidSentAddresses();
        printEvent(event, add);
        System.out.println(
"以上地址部分发送成功.");
    }


    
public void printEvent(TransportEvent event, Address add[])
    
{
        System.out.println(
"**************************************");
        System.out.println(
"evnet==" + event.getMessage().toString());
        
if(add != null)
        
{
            
for(int i = 0; i < add.length; i++)
                System.out.println(add[i].toString());

        }

    }


    
private String user;
    
private String password;
    
private String fromAddress;
    
private String smtpServerDns;
    
private boolean authFlag;
    
private String receiver[];
    
private String title;
    
private String content;
    
private String mimeType;
    
private ArrayList accessories;
    
private Session session;
    
private MimeMessage mimeMesg;
}


------------------------------------------------------

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator
{

    
public MailAuthenticator()
    
{
        user 
= "";
        password 
= "";
    }


    
public MailAuthenticator(String user, String password)
    
{
        
this.user = user;
        
this.password = password;
    }


    
public MailAuthenticator(String user)
    
{
        
this.user = user;
        password 
= "";
    }


    
public PasswordAuthentication getPasswordAuthentication()
    
{
        
return new PasswordAuthentication(user, password);
    }


    
private String user;
    
private String password;
}


 

 
 
阅读更多
个人分类: Network
上一篇Socket实现的SMTP邮件发送客户端。
下一篇JavaMail POP3 client
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭