android利用javamail实现后台发送可添加附件的邮件

android利用javamail实现后台发送可添加附件的邮件
2011-07-24 19:09

android中实现利用javamail的包发送邮件,代码如下

 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,所以导致原来的代码无法运行。

运行本程序需要的包需要在project->properties->java build path中导入。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值