package utils;import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.sql.*;
import java.io.*;
//import org.apache.soap.util.mime.*; //for ByteArrayDataSource
import javax.activation.DataSource; //for ByteArrayDataSourcepublic class JavaSMTPMail {
private String host ;
private String from ;
private String to ;
private String subject;
private String body ;
private String fileAttachment ;public void send() throws Exception {host = "purfax"; //(String) p.get("MAIL_SERVER");
host = "wuyg"; //(String) p.get("MAIL_SERVER");
from = "purfaxbox@purfax";//(String) p.get("MAIL_USER")+"@"+host;
System.out.print(from);
// to = (String) items.get("to");
to ="[email protected]";subject = "test fax中文 --2"; // (String) items.get("subject");
// subject = "[email protected] | 363826 | 1";
body = "test fax from wuyg"; // (String) items.get("body");
// fileAttachment = "D:/Fax_Log/domino.log.txt"; //a_attachFile;
fileAttachment = "d:/testQInput.htm"; //a_attachFile;// Get system properties
Properties props = System.getProperties();// Setup mail server
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "false");// Get session
Session session =
Session.getInstance(props, null);// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom( new InternetAddress(from));
message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// 建议改成下面的语句
// sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
// message.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();// 插入正文
if (body !="") {
messageBodyPart.setHeader("Content-Type","text/plain; charset=gb2312");
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
}// 插入附件
if (fileAttachment != ""){
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
// messageBodyPart.setDataHandler( new DataHandler(source));
// messageBodyPart.setFileName(fileAttachment);
//建议改用下面的方法
String SSS="--wuyg abcd--123445667788 asdfad asdadasd --中文--";ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
ObjectOutputStream objectStream=new ObjectOutputStream(byteStream);
objectStream.writeObject(SSS); //theObject);
// messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(byteStream.toByteArray(), "lotontech/javaobject")));
//
// messageBodyPart.setHeader("Content-Type","application/octet-stream; name=a.txt");
// messageBodyPart.setHeader("Content-Disposition", "attachment;filename=a.txt");
// messageBodyPart.setHeader("Content-transfer-encoding", "base64");
// messageBodyPart.setHeader("Content-Type","text/csv");
// DataSource source = new ByteArrayOutputStream(SSS);
// messageBodyPart.setDataHandler(new DataHandler(source));
InternetHeaders cc = new InternetHeaders();
cc.setHeader("Content-Type","application/octet-stream; name=a.txt");
cc.setHeader("Content-Disposition", "attachment;filename=a.txt");
// cc.setHeader("Content-transfer-encoding", "base64");
MimeBodyPart vv =new MimeBodyPart(cc,byteStream.toByteArray());
MimePartDataSource bb=new MimePartDataSource(vv);
messageBodyPart.setDataHandler(new DataHandler(bb));
// messageBodyPart.setDataHandler(new DataHandler(SSS, "lotontech/javaobject"));
// messageBodyPart.setDataHandler(new DataHandler(SSS.toCharArray(), "Content-type:text/csv"));
// messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(SSS), "Content-type:text/csv"));
// messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
}//Put parts in message
message.setContent(multipart);// Send the message
System.out.println();
System.out.println("发送到:"+ to );
Transport.send( message );
}
}

解决方案 »

  1.   

    代码太长,你给我发个邮件[email protected]
      

  2.   

    import java.util.*;import javax.mail.*;
    import javax.mail.internet.*;/**
     * <p>Title: java mail</p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2004</p>
     * <p>Company: </p>
     * @author petehero
     * @version 1.0
     */class SendMail
    {
    /**
     * Logger for this class
     */






    private static String server = "smtp.163.com";//smtp主机名。
    private static String from = "[email protected]";//发送方邮件地址
    private static String pw = "XXXXXX";//发送方邮件密码。
    private static String to = "[email protected]"; //接收方邮件地址
     static String subject="hello";
    /*BodyPart bp = new MimeBodyPart();
    Multipart mp = new MimeMultipart();
    DataSource source = new FileDataSource("a.jpg");//附件
    */

     static String mailContent="你好!\n\n"+"\t邮件正文test\n\n";//邮件正文   
        public static void send()
        {
        
            try
            {
                Properties props = new Properties();
                Session sendMailSession;
                Store store;
                Transport transport;
                props.put("mail.smtp.auth","true");
                props.put("mail.smtp.host",server); 
                props.put("mail.smtp.user",from); 
                props.put("mail.smtp.password",pw); 
                //PopupAuthenticator popA=new PopupAuthenticator();
                //PasswordAuthentication pop = popA.performCheck(from, pw);
                //sendMailSession = Session.getInstance(props,popA);//填写用户名及密码
                sendMailSession = Session.getInstance(props,new Authenticator(){ 
    public  PasswordAuthentication getPasswordAuthentication() //邮件安全认证。

        return new PasswordAuthentication(from, pw); 

    });
                
                
                
                Message newMessage = new MimeMessage(sendMailSession);
                newMessage.setFrom(new InternetAddress(from));
                newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
                newMessage.setSubject(subject);
                newMessage.setSentDate(new Date());
                /*
                bp.setText("bptext");
                mp.addBodyPart(bp);
                bp = new MimeBodyPart();
                bp.setDataHandler(new DataHandler(source));
                bp.setFileName("141.txt");
                mp.addBodyPart(bp);
                newMessage.setContent(mp);
                */
                mailContent+=new Date().toLocaleString();
                newMessage.setText(mailContent); 
                transport = sendMailSession.getTransport("smtp");
                //System.out.println("Sending...");
                //transport
                Transport.send(newMessage);
                //Transport.send(newMessage );
                //System.out.println(server+from+pw+to);        }
            catch (MessagingException ex)
            {

            }
        }
    //    public static void main(String[] args)
    //    {   
    //    
    ////     for(int i=0;i<args.length;i++)
    ////     {
    ////     System.out.println(args[i]);
    ////     }
    //    
    //     from=args[0].trim();
    ////    
    //     pw=args[1].trim();
    ////    
    //        SendMail sml = new SendMail();
    //      sml.send();
    ////     String a=SendMail.mailSend("hello","world");
    ////     System.out.println(a);
    //    }
        static String mailSend(String t_to,String t_subject,String t_text)
        {   String state="";
        to=t_to;
        subject=t_subject;
        
        mailContent=t_text+"\n\n";
        SendMail sml = new SendMail();
        sml.send();
        state="Successful";
        
         return state;
        }  /*  public class PopupAuthenticator extends Authenticator{
            String username=null;
            String password=null;
            public PopupAuthenticator(){}
            public PasswordAuthentication performCheck(String user,String pass){
                username = user;
                password = pass;
                return getPasswordAuthentication();
            }
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }    }*/
    }
      

  3.   

    利用 Java Mail 来收发邮件 
    --------------------------------------------------------------------------------
    随着网络应用的不断推广,电子邮件越来越多的被大家使用。虽然我们往往将电子邮件与 Foxmail、Outlook 这样的电子邮件客户端联系起来,但是往往我们也需要自己编程实现发送接收邮件,例如在一个网站注册用户后网站发出的回执mail,或者在网络购物的时候,在完成订单后的几分钟之内发送确认电子邮件。对于这样的需求,我们不能通过已有的邮件客户端而需要自己编写邮件发送或者处理程序。在这里向大家讲解一下如何利用JavaMail来实现邮件的收发。注意:本文只打算讨论JavaMail收发带附件邮件的一些技巧,所以只是给出部分代码
    1.发送带附件的邮件我们平时发送的邮件主要可以分解成2大部分,一个是发信人,接信人,主题等邮件标头,另外一部分是邮件内容,它包括了邮件的附件。我们在发送普通邮件的时候content设置的类型是"text/html",带上附件后,我们需要把content的类型设置成Multipart,这时content包括了附件和"text/html"类型的正文。下面的这个告诉大家如何把附件放置到邮件中。
    private Multipart getMultipart() throws MessagingException,UnsupportedEncodingException { 
    MimeMultipart mp = new MimeMultipart(); 
    try 

    //设置content里的内容 
    MimeBodyPart contentMbp = new MimeBodyPart(); 
    //请指定字符集,否则会是乱码 
    contentMbp.setContent(_mailContent.getContent(),
    "text/html; charset=GB2312"); 
    mp.addBodyPart(contentMbp); 
    //添加附件 
    for (int i=0;i<_mailAttachment.getAttachPath().size();i++)

    MimeBodyPart mbp = new MimeBodyPart(); 
    FileDataSource fds = new FileDataSource((String)
    _mailAttachment.getAttachPath().get(i)); 
    mbp.setDataHandler(new DataHandler(fds)); 
    mbp.setFileName(MimeUtility.encodeWord(fds.getName(),
    "GB2312",null)); 
    mp.addBodyPart(mbp); 
    }

    catch(MessagingException ie) 

    System.out.println("Set Content Message error..."+ie.getMessage()); 
    throw ie; 

    catch(UnsupportedEncodingException ie) 

    System.out.println("Encode the fileName error..."+ie.getMessage()); 
    throw ie; 

    return mp; 
    }
    放置附件的注意事项如下:
    在发mail时需要注意字符集的问题。不但content里要设置,而且文件名也需要设置。如果我们去掉mbp.setFileName(MimeUtility.encodeWord(fds.getName(),"GB2312",null));这句话,那么你选中的附件还是会带到邮件里,但是在附件里看不到。我们可以通过查看邮件大小知道。我们利用这个特点来实现发送content中写的是html语言,而且包含图片信息的邮件。2.发送content中包含html页面的邮件大家都知道html语言可以带上图片链接(),那么我们在发送邮件的时候就需要对这些链接的图片做特殊处理。否则在对方接收到邮件的时候会看不到图片。我们特殊处理的方法就是把它们当成附件发送,但不显示在附件里。要做到这些就首先需要对输入的content进行解析,找到所带图片的路径。然后把content中这段代码变成。我们在发送附件的时候用mbp1.setHeader("Content-ID","IMG") 来把图片和附件对应上。如何具体解析content的操作我就不赘述了,我现在给出如何把修改好的content发送出去的例子。
    //对于发送html类型的content。里边包括图片。 
    for(int i=0;i<_mailContent.getImgHash().size();i++) 

    MimeBodyPart mbp1 = new MimeBodyPart();
    //得到图片的数据
    FileDataSource fds = new FileDataSource(
    (String)_mailContent.getImgHash().get("IMG"+i)); 
    //设置到MimeBodyPart中
    mbp1.setDataHandler(new DataHandler(fds)); 
    //设置图片附件和html的对应关系
    mbp1.setHeader("Content-ID","IMG"+i); 
    mp.addBodyPart(mbp1); 
    }3.邮件的状态我们在阅读完邮件后可以给邮件设置删除标志,然后在关闭FOLDER的时候用true来清空已经被标志为删除的邮件。邮件的状态是在类FLAGS.FLAG中定义的。包括如下几种:
    Flags.Flag.ANSWERED 
    Flags.Flag.DELETED 
    Flags.Flag.DRAFT 
    Flags.Flag.FLAGGED 
    Flags.Flag.RECENT 
    Flags.Flag.SEEN 
    Flags.Flag.USER 我们可以根据不同的需要进行设置,但是需要注意的是,不是所有的服务器都支持这些状态。我们在做操作之前可以用getPermanentFlags方法来得到Message中的状态。参考下面代码
    Message m = folder.getMessage(1); 
    // set the DELETED flag 
    m.setFlag(Flags.Flag.DELETED, true); 
    // Check if DELETED flag is set of this message 
    if (m.isSet(Flags.Flag.DELETED)) 
    System.out.println("DELETED message"); 
    // Examine ALL system flags for this message 
    Flags flags = m.getFlags(); 
    Flags.Flag[] sf = flags.getSystemFlags(); 
    for (int i = 0; i < sf.length; i++) 

    if (sf[i] == Flags.Flag.DELETED) 
    System.out.println("DELETED message"); 
    else if (sf[i] == Flags.Flag.SEEN) 
    System.out.println("SEEN message"); 
    }4.接收带附件的邮件在带有附件的邮件中,消息的内容是Multipart型,这样我们就需要解析它来得到content和附件(它是发送带附件的邮件的逆向过程)。大家在使用outlook、foxmail这些电子邮件客户端的时候会发现,我们的邮件被从服务器上下载下来并且保存到本地硬盘上了,这种方式方便我们离线浏览邮件。在下面的范例中我们也把服务器上的邮件保存到本地。如果有兴趣大家可以编写一个客户端的图形界面来读取保存下来的邮件。
    在下面的例子里,我只是向大家介绍如何解析附件。
    private void getAttachFile(Part messagePart,BufferedOutputStream writeAttachObj) 
    throws IOException, MessagingException 

    Object content = messagePart.getContent() ; 
    try 

    //这种情况下的邮件都是用multi模式发送的,
    // 这种模式包括有附件的邮件和用html表示content的邮件 
    if (content instanceof Multipart) 

    Multipart contentTmp = (Multipart) content ; 
    //如果是MULTI模式发送的,BodyPart(0).getContent()肯定就是content 
    System.out.println("content==" + contentTmp.getBodyPart(0).getContent()) ; 
    //getCount()可以得到content中bodyPart的个数,content就是第一个
    //bodyPart,其它的附件按照顺序类推。但是有的时候附件就是另外一个邮件,
    //而这个邮件里边可能有其他的附件。下面代码用循环对嵌套情况进行解析。
    for (int i = 0 ; i < contentTmp.getCount() ; i++) 

    if (contentTmp.getBodyPart(i).isMimeType("multipart/*")) 

    Multipart multipart = (Multipart) 
    contentTmp.getBodyPart(i).getContent() ;
    //这个地方增加循环是为了解决嵌套附件的情况。
    for (int k = 0 ; k < multipart.getCount() ; k++) 

    //content也会存在于INPUTSTREAM中。 
    saveAttacheFile(multipart.getBodyPart(k).getContentType(), 
    multipart.getBodyPart(k).getDisposition(), 
    multipart.getBodyPart(k).getFileName(), 
    multipart.getBodyPart(k).getInputStream(), 
    writeAttachObj); 


    else 

    saveAttacheFile(contentTmp.getBodyPart(i).getContentType(), 
    contentTmp.getBodyPart(i).getDisposition(), 
    contentTmp.getBodyPart(i).getFileName(), 
    contentTmp.getBodyPart(i).getInputStream(), 
    writeAttachObj); 



    //这种情况中邮件是纯文本形式,并且没有附件 
    else 

    writeAttachObj.write(("content = "+content+"
    ").getBytes()); 
    writeAttachObj.flush(); 


    catch (Exception ie) 

    System.out.println("exception====" + ie.getMessage()) ; 

    }
     
      

  4.   

    给你个例子
    /*
     * ————邮件订阅系统
     * Created on 2005-12-15
     * Author     fhp
     * 功能描述————邮件对象构造
     * TODO To change the template for this generated file go to
     * Window - Preferences - Java - Code Style - Code Templates
     */import java.util.Properties;import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Address;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;/**
     * @author Administrator
     *
     * TODO To change the template for this generated type comment go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    public class MailConstructor { //private String EnvelopeFrom; //邮件发送地址
    //private String MailHost; //邮件服务器
    private String UserName; //用户名
    private String PassWord; //用户密码
    private MimeMessage mimeMsg;  //MIME邮件对象
    private Session session;  //邮件会话对象
    private Properties props;  //系统属性
    //private boolean needAuth = false;  //smtp是否需要认证
    private Multipart mp;  //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

    public MailConstructor () {

    }
    /**
    public void sendMail() {
    setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取
    createMimeMessage();
    }
    **/
    public MailConstructor(String smtp){
    setSmtpHost(smtp);
    createMimeMessage();
    }
    /**
    * @param hostName String
    */
    public void setSmtpHost(String hostName) {

    System.out.println("设置系统属性:mail.smtp.host = "+hostName);
    if(props == null)props = System.getProperties();  //获得系统属性对象
    props.put("mail.smtp.host",hostName);  //设置SMTP主机
    }

    /**
    * @return boolean
    */
    public boolean createMimeMessage() {
    try {
    System.out.println("准备获取邮件会话对象!");
    session = Session.getDefaultInstance(props,null);  //获得邮件会话对象
    } catch(Exception e){
    System.err.println("获取邮件会话对象时发生错误!"+e);
    return false;
    }

    System.out.println("准备创建MIME邮件对象!");
    try{
    mimeMsg = new MimeMessage(session);  //创建MIME邮件对象
    mp = new MimeMultipart();
    return true;
    } catch(Exception e){
    System.err.println("创建MIME邮件对象失败!"+e);
    return false;
    }
    }
    /**
    * @param need boolean
    */
    public void setNeedAuth(boolean need) {
    System.out.println("设置smtp身份认证: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 String
    * @param pass String
    */
    public void setNamePass(String name,String pass) {
    UserName = name;
    PassWord = pass;
    }
    /**
    * @param mailSubject String
    * @return boolean
    */
    public boolean setSubject(String mailSubject) {
    System.out.println("设置邮件主题!");
    try{
    mimeMsg.setSubject(mailSubject);
    return true;
    } catch(Exception e) {
    System.err.println("设置邮件主题发生错误!");
    return false;
    }
    }
    /**
    * @param mailBody String
    */
    public boolean setBody(String mailBody) {
    try{
    BodyPart bp = new MimeBodyPart();
    bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody,"text/html;charset=GB2312");
    mp.addBodyPart(bp);
    return true;
    } catch(Exception e){
    System.err.println("设置邮件正文时发生错误!"+e);
    return false;
    }
    }
    /**
    * @param name String
    * @param pass String
    */
    public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:"+filename);
    try{
    BodyPart bp = new MimeBodyPart();
    FileDataSource fileds = new FileDataSource(filename);
    bp.setDataHandler(new DataHandler(fileds));
    bp.setFileName(fileds.getName());
    mp.addBodyPart(bp);
    return true;
    } catch(Exception e){
    System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
    return false;
    }
    }
    /**
    * @param name String
    * @param pass String
    */
    public boolean setFrom(String from) {
    System.out.println("设置发信人!");
    try{
    mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
    return true;
    } catch(Exception e) {
    return false; 
    }
    }
    /**
    * @param name String
    * @param pass String
    */
    public boolean setTo(String to){
    if(to == null)return false;

    try {
    mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
    return true;
    } catch(Exception e) {
    return false;
    }
    }
    /**
    * @param name String
    * @param pass String
    */
    public boolean setCopyTo(String copyto) {
    if(copyto == null)return false;
    try{
    mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
    return true;
    } catch(Exception e) {
    return false;
    }
    }
    /**
    * @param name String
    * @param pass String
    */
    public boolean sendout() {
    try{
    mimeMsg.setContent(mp);
    mimeMsg.saveChanges();
    System.out.println("正在发送邮件....");

    Session mailSession = Session.getInstance(props,null);
    Transport transport = mailSession.getTransport("smtp");
    transport.connect((String)props.get("mail.smtp.host"),UserName,PassWord);
    transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
    //transport.send(mimeMsg);

    System.out.println("发送邮件成功!");
    transport.close();

    return true;
    } catch(Exception e) {
    System.err.println("邮件发送失败!"+e);
    return false;
    }
    } /**
    * Just do it as this
    */
    public static void main(String[] args) { String mailbody = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+
    "<div align=center><a href=http://www.csdn.net> csdn </a></div>";

    MailConstructor themail = new MailConstructor("smtp.163.com");
    themail.setNeedAuth(true);

    if(themail.setSubject("标题") == false) return;
    if(themail.setBody(mailbody) == false) return;
    if(themail.setTo("[email protected],[email protected],[email protected]") == false) return;
    if(themail.setFrom("[email protected]") == false) return;
    //if(themail.addFileAffix("c:\\boot.ini") == false) return;
    themail.setNamePass("solo","3355");

    if(themail.sendout() == false) return; 
    }
    }
    /**
     * 
     * @author Administrator
     *
     * TODO To change the template for this generated type comment go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    class SMTPAuth extends javax.mail.Authenticator {
    private String user, password;

    public SMTPAuth(String u, String p) {
    user = u;
    password = p;
    }
    public void getuserinfo(String getuser, String getpassword) {
    user = getuser;
    password = getpassword;
    }
    protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
    return new javax.mail.PasswordAuthentication(user, password);
    }
    }
      

  5.   

    可以发送附件的例子
    http://www.blogjava.net/sunfruit/archive/2006/02/19/31523.html