您的位置:首页 > 移动开发 > Android开发

android 通过通过javaemail 来发送email 无需系统支持,无需配置

2013-08-16 15:22 489 查看
该应用源代码下载地址:http://download.csdn.net/detail/ygn918042354/5960063

1 需要下载三个包:

http://code.google.com/p/javamail-android/downloads/list

2 下载后需要配置 如果是导入的工程,需要通过下面方式配置
http://blog.sina.com.cn/s/blog_6966c76b01011fye.html
3 在里面修改邮箱名字和密码.如果不对,是无法发送的,

看下发送方式:

1 EmailSender sender = new EmailSender();

                //设置服务器地址和端口,网上搜的到

                 sender.setProperties("smtp.126.com", "25");

                //分别设置发件人,邮件标题和文本内容

                try {

                    sender.setMessage("yangguannanguannan@126.com", "EmailSender", "This is from JavaMail !");

                    sender.setReceiver(new String[]{"yangguannanguannan@126.com"});

                    sender.sendEmail("smtp.126.com", "yangguannanguannan@126.com", "mima");

                } catch (AddressException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (MessagingException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

需要 EmailSender.java

package src.icetest;

import java.io.File;

import java.util.Date;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Address;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class EmailSender {

    private Properties properties;

    private Session session;

    private Message message;

    private MimeMultipart multipart;

    public EmailSender() {

            super();

            this.properties = new Properties();

    }

    public void setProperties(String host,String post){

            //地址

            this.properties.put("mail.smtp.host",host);

            //端口号

            this.properties.put("mail.smtp.post",post);

            //是否验证

            this.properties.put("mail.smtp.auth",true);

            this.session=Session.getInstance(properties);

            this.message = new MimeMessage(session);

            this.multipart = new MimeMultipart("mixed");

    }

    /**

     * 设置收件人

     * @param receiver

     * @throws MessagingException

     */

    public void setReceiver(String[] receiver) throws MessagingException{

            Address[] address = new InternetAddress[receiver.length];

            for(int i=0;i<receiver.length;i++){

                    address[i] = new InternetAddress(receiver[i]);

            }

            this.message.setRecipients(Message.RecipientType.TO, address);

    }

    /**

     * 设置邮件

     * @param from 来源

     * @param title 标题

     * @param content 内容

     * @throws AddressException

     * @throws MessagingException

     */

    public void setMessage(String from,String title,String content) throws AddressException,

MessagingException{

            this.message.setFrom(new InternetAddress(from));

            this.message.setSubject(title);

            //纯文本的话用setText()就行,不过有附件就显示不出来内容了

            MimeBodyPart textBody = new MimeBodyPart();

            textBody.setContent(content,"text/html;charset=gbk");

            this.multipart.addBodyPart(textBody);

    }

    /**

     * 添加附件

     * @param filePath 文件路径

     * @throws MessagingException

     */

    public void addAttachment(String filePath) throws MessagingException{

            FileDataSource fileDataSource = new FileDataSource(new File(filePath));

            DataHandler dataHandler = new DataHandler(fileDataSource);

            MimeBodyPart mimeBodyPart = new MimeBodyPart();

            mimeBodyPart.setDataHandler(dataHandler);

            mimeBodyPart.setFileName(fileDataSource.getName());

            this.multipart.addBodyPart(mimeBodyPart);

    }

    /**

     * 发送邮件

     * @param host 地址

     * @param account 账户名

     * @param pwd 密码

     * @throws MessagingException

     */

    public void sendEmail(String host,String account,String pwd) throws MessagingException{

            //发送时间

            this.message.setSentDate(new Date());

            //发送的内容,文本和附件

            this.message.setContent(this.multipart);

            this.message.saveChanges();

            //创建邮件发送对象,并指定其使用SMTP协议发送邮件  

            Transport transport=session.getTransport("smtp");  

            //登录邮箱  

            transport.connect(host,account,pwd);  

            //发送邮件

            transport.sendMessage(message, message.getAllRecipients());

            //关闭连接

            transport.close();

    }

}

第2中方式:

Mails2 m = new Mails2("918042354@qq.com", "mima");

        m.set_debuggable(false);

        String[] toArr = {"918042354@qq.com"};

        m.set_to(toArr);

        m.set_from("918042354@qq.com");

        m.set_subject("This is an email sent using icetest from an Android device");

        m.setBody("Email body. test by Java Mail final");

        try {

            //m.addAttachment("/sdcard/filelocation");

            if(m.send()) {

            Log.i("IcetestActivity","Email was sent successfully.");

                        

            } else {

                Log.i("IcetestActivity","Email was sent failed.");

            }

        } catch (Exception e) {

            // Toast.makeText(MailApp.this,

            // "There was a problem sending the email.",

            // Toast.LENGTH_LONG).show();

            Log.e("MailApp", "Could not send email", e);

        }

需要 Mails2.java

package src.icetest;

 

import java.util.Date;

import java.util.Properties;

 

import javax.activation.CommandMap;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.activation.MailcapCommandMap;

import javax.mail.BodyPart;

import javax.mail.Multipart;

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 Mails2 extends javax.mail.Authenticator {

    private String _user;

    private String _pass;

    private String[] _to;

    private String _from;

    private String _port;

    private String _sport;

    private String _host;

    private String _subject;

    private String _body;

    private boolean _auth;

    private boolean _debuggable;

    private Multipart _multipart;

 

    public Mails2() {

        _host = "smtp.qq.com"; // default smtp server

        _port = "465"; // default smtp port

        _sport = "465"; // default socketfactory port

        _user = ""; // username _pass = ""; // password

        _from = ""; // email sent from

        _subject = ""; // email subject

        _body = ""; // email body

        _debuggable = false; // debug mode on or off - default off

        _auth = true; // smtp authentication - default on

        _multipart = new MimeMultipart(); // There is something wrong with

                                            // MailCap, javamail can not find a

                                            // handler for the multipart/mixed

                                            // part, so this bit needs to be

                                            // added.

        MailcapCommandMap mc = (MailcapCommandMap) CommandMap

                .getDefaultCommandMap();

        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");

        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");

        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");

        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");

        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");

        CommandMap.setDefaultCommandMap(mc);

    }

 

    public String get_user() {

        return _user;

    }

 

    public void set_user(String _user) {

        this._user = _user;

    }

 

    public String get_pass() {

        return _pass;

    }

 

    public void set_pass(String _pass) {

        this._pass = _pass;

    }

 

    public String[] get_to() {

        return _to;

    }

 

    public void set_to(String[] _to) {

        this._to = _to;

    }

 

    public String get_from() {

        return _from;

    }

 

    public void set_from(String _from) {

        this._from = _from;

    }

 

    public String get_port() {

        return _port;

    }

 

    public void set_port(String _port) {

        this._port = _port;

    }

 

    public String get_sport() {

        return _sport;

    }

 

    public void set_sport(String _sport) {

        this._sport = _sport;

    }

 

    public String get_host() {

        return _host;

    }

 

    public void set_host(String _host) {

        this._host = _host;

    }

 

    public String get_subject() {

        return _subject;

    }

 

    public void set_subject(String _subject) {

        this._subject = _subject;

    }

 

    public String get_body() {

        return _body;

    }

 

    public void set_body(String _body) {

        this._body = _body;

    }

 

    public boolean is_auth() {

        return _auth;

    }

 

    public void set_auth(boolean _auth) {

        this._auth = _auth;

    }

 

    public boolean is_debuggable() {

        return _debuggable;

    }

 

    public void set_debuggable(boolean _debuggable) {

        this._debuggable = _debuggable;

    }

 

    public Multipart get_multipart() {

        return _multipart;

    }

 

    public void set_multipart(Multipart _multipart) {

        this._multipart = _multipart;

    }

 

    public Mails2(String user, String pass) {

        this();

        _user = user;

        _pass = pass;

    }

 

    public boolean send() throws Exception {

        Properties props = _setProperties();

        if (!_user.equals("") && !_pass.equals("") && _to.length > 0

                && !_from.equals("") && !_subject.equals("")

                && !_body.equals("")) {

            Session session = Session.getInstance(props, this);

            MimeMessage msg = new MimeMessage(session);

            msg.setFrom(new InternetAddress(_from));

            InternetAddress[] addressTo = new InternetAddress[_to.length];

            for (int i = 0; i < _to.length; i++) {

                addressTo[i] = new InternetAddress(_to[i]);

            }

            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

            msg.setSubject(_subject);

            msg.setSentDate(new Date()); // setup message body

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText(_body);

            _multipart.addBodyPart(messageBodyPart); // Put parts in message

            msg.setContent(_multipart); // send email

            Transport.send(msg);

            return true;

        } else {

            return false;

        }

    }

 

    public void addAttachment(String filename) throws Exception {

        BodyPart messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        _multipart.addBodyPart(messageBodyPart);

    }

 

    @Override

    public PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication(_user, _pass);

    }

 

    private Properties _setProperties() {

        Properties props = new Properties();

        props.put("mail.smtp.host", _host);

        if (_debuggable) {

            props.put("mail.debug", "true");

        }

        if (_auth) {

            props.put("mail.smtp.auth", "true");

        }

        props.put("mail.smtp.port", _port);

        props.put("mail.smtp.socketFactory.port", _sport);

        props.put("mail.smtp.socketFactory.class",

                "javax.net.ssl.SSLSocketFactory");

        props.put("mail.smtp.socketFactory.fallback", "false");

        return props;

    } // the getters and setters

 

    public String getBody() {

        return _body;

    }

 

    public void setBody(String _body) {

 

        this._body = _body;

    } // more of the getters and setters ��.. }

}

都已经实验过,很爽.

以后如果想检测用户的简单操作,完全可以使用这种方式来做.还省了服务器.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐