---
title: "android中实现利用javamail的包发送邮件"
author: "mars5337"
date: "2010-09-15T00:09:25Z"
tags: []
categories: ["移动开发"]
slug: "android-javamail"
draft: false
lastmod: "2010-09-15T00:09:25Z"
id: 763449
url: "https://mars5337.iteye.com/blog/763449"
---

package com.Mail;
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText;
public class Mail extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);
        //initial 
        final Button send = (Button) this.findViewById(R.id.send); 
        final EditText userid = (EditText) this.findViewById(R.id.userid); 
        final EditText password = (EditText) this.findViewById(R.id.password); 
        final EditText from = (EditText)this.findViewById(R.id.from); 
        final EditText to = (EditText)this.findViewById(R.id.to); 
        final EditText subject = (EditText)this.findViewById(R.id.subject); 
        final EditText body = (EditText)this.findViewById(R.id.body);
        send.setOnClickListener(new View.OnClickListener() {
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub
                GMailSender sender = new GMailSender("yourid@gmail.com",//userid.getText().toString(), 
                        "password");//password.getText().toString()); 
                try { 
                    sender.sendMail( 
                            //subject.getText().toString(), 
                            "about Hello Wrold by email", 
                            //body.getText().toString(), 
                            "body of the word", 
                            //from.getText().toString(), 
                            "yourid@gmail.com", 
                            //to.getText().toString()); 
                            "receipentid@gmail.com"); 
                } catch (Exception e) { 
                    Log.e("SendMail", e.getMessage(), e); 
                }
            } 
        }); 
    } 
}
 
package com.Mail;
import java.io.ByteArrayInputStream; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Properties;
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.mail.Authenticator; 
import javax.mail.BodyPart; 
import javax.mail.Message; 
import javax.mail.Part; 
import javax.mail.PasswordAuthentication; 
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;
public class GMailSender extends javax.mail.Authenticator { 
    private String mailhost = "smtp.gmail.com"; 
    private String user; 
    private String password; 
    private Session session;
    public GMailSender(String user, String password) { 
        this.user = user; 
        this.password = password;
        /* 
         * Properties props = new Properties(); 
         * props.setProperty("mail.transport.protocol", "smtp"); 
         * props.setProperty("mail.host", mailhost); props.put("mail.smtp.auth", 
         * "true"); props.put("mail.smtp.user", this.user); 
         * props.put("mail.smtp.password", this.password); 
         * 
         * props.put("mail.smtp.port", "465"); 
         * props.put("mail.smtp.socketFactory.port", "465"); 
         * props.put("mail.smtp.socketFactory.class", 
         * "javax.net.ssl.SSLSocketFactory"); 
         * props.put("mail.smtp.socketFactory.fallback", "false"); 
         * props.setProperty("mail.smtp.quitwait", "false"); session = 
         * Session.getDefaultInstance(props, this); 
         */
        Properties props = new Properties(); 
        //props.setProperty("mail.transport.protocol", "smtp");  
        props.put("mail.smtp.host", mailhost); 
        props.put("mail.smtp.port", "587"); 
        // Enable authentication if emailProperties.getSmtpUser() is not null 
        if (this.user != null) { 
            props.put("mail.smtp.auth", "true"); 
        } 
        props.put("mail.smtp.user", this.user); 
        props.put("mail.smtp.password", this.password); 
        props.put("mail.smtp.starttls.enable","true"); 
        /**seesion class 
         * this class use as the total application environment information 
         * and collect the Client with the server to build the net connect conversion information 
         * */ 
        this.session = Session.getDefaultInstance(props, new Authenticator() { 
            protected PasswordAuthentication getPasswordAuthentication() { 
                return new PasswordAuthentication("yourid", 
                        "password"); 
            } 
        }); 
    }
    public synchronized void sendMail(String subject, String body, 
            String sender, String recipients) throws Exception { 
        MimeMessage message = new MimeMessage(session); 
        message.setSender(new InternetAddress(sender)); 
        message.setSubject(subject); 
        message.setText(body); 
        //add attachment 
        try 
        { 
            MimeMultipart allMultipart = new MimeMultipart("mixed"); 
            MimeBodyPart attachPartPicture = createAttachment("/sdcard/androidManifest.xml"); 
            allMultipart.addBodyPart(attachPartPicture); 
            message.setContent(allMultipart); 
            message.saveChanges(); 
        } 
        catch(Exception e) 
        { 
            System.out.print(e.getMessage()); 
        } 
        //judge multi-recipient or one recipient 
        if (recipients.indexOf(',') > 0) 
            message.setRecipients(Message.RecipientType.TO, InternetAddress 
                    .parse(recipients)); 
        else 
            message.setRecipient(Message.RecipientType.TO, new InternetAddress( 
                    recipients)); 
        try { 
            session.setDebug(true); 
            Transport.send(message); 
        } catch (Exception e) { 
            System.out.println(e.getMessage()); 
        } 
    }
    private static MimeBodyPart createAttachment(String filename) throws Exception { 
        // TODO Auto-generated method stub 
        MimeBodyPart attachPart = new MimeBodyPart(); 
        FileDataSource fds = new FileDataSource(filename); 
        attachPart.setDataHandler(new DataHandler(fds)); 
        attachPart.setFileName(fds.getName()); 
        return attachPart; 
    }
    public class ByteArrayDataSource implements DataSource { 
        private byte data; 
        private String type;
        public ByteArrayDataSource(byte data, String type) { 
            super(); 
            this.data = data; 
            this.type = type; 
        }
        public ByteArrayDataSource(byte data) { 
            super(); 
            this.data = data; 
        }
        public void setType(String type) { 
            this.type = type; 
        }
        public String getContentType() { 
            if (type == null) 
                return "application/octet-stream"; 
            else 
                return type; 
        }
        public InputStream getInputStream() throws IOException { 
            return new ByteArrayInputStream(data); 
        }
        public String getname() { 
            return "ByteArrayDataSource"; 
        }
        public OutputStream getOutputStream() throws IOException { 
            throw new IOException("Not Supported"); 
        }
        @Override 
        public String getName() { 
            // TODO Auto-generated method stub 
            return null; 
        } 
    }
}
可能因为某些参数的问题所以导致代码运行存在一点问题，大家只要修改参数就可以了，我和原代码比较了一下
发现问题在于端口props.put("mail.smtp.port", "587");props.put("mail.smtp.starttls.enable","true");
注意噢，587对应的是startttls，原来的代码中使用的465端口应该使用的是ssl，所以导致原来的代码无法运行。
运行本程序需要的包有activation.jar 、additionnal.jar，mail.jar，需要在project->properties->java build path中导入。