Monday 15 December 2014

Send Email with attachment without Intent

                                   Send Email with attachment without Intent


     Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at

Android Sending Email wihtout intent

 Step:1
activity_mail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

 xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity"

    android:background="@drawable/bg">


    <Button

        android:id="@+id/send"

        android:layout_width="150dp"

        android:layout_height="70dp"

        android:layout_centerInParent="true"

        android:background="@drawable/buttonclickcolor"

        android:text="Send Mail" />



</RelativeLayout>




Step:2

GMailSender.java


import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

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;  

import java.io.ByteArrayInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.security.Security;

import java.util.Properties;


public class GMailSender extends javax.mail.Authenticator {

private String mailhost = "smtp.gmail.com";

    private String user;

    private String password;

    private Session session;
    

    private Multipart _multipart = new MimeMultipart();

    static {

        Security.addProvider(new com.protect.appsecure.JSSEProvider());

    }

     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.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);

    }

    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication(user, password);

    }
 
    public synchronized void sendMail(String subject, String body,

            String sender, String recipients) throws Exception {

        try {

            MimeMessage message = new MimeMessage(session);

            DataHandler handler = new DataHandler(new ByteArrayDataSource(

                    body.getBytes(), "text/plain"));

            message.setSender(new InternetAddress(sender));

            message.setSubject(subject);

            message.setDataHandler(handler);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText(body);

            _multipart.addBodyPart(messageBodyPart);



            // Put parts in message

            message.setContent(_multipart);

            if (recipients.indexOf(',') > 0)

                message.setRecipients(Message.RecipientType.TO,

                        InternetAddress.parse(recipients));

            else

                message.setRecipient(Message.RecipientType.TO,

                        new InternetAddress(recipients));

            Transport.send(message);

        } catch (Exception e) {
 
        }

    }
 
    public void addAttachment(String filename) throws Exception {

        BodyPart messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName("download image");

         _multipart.addBodyPart(messageBodyPart);

    }
 
    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");

        }

    }

}




Step:3

   
import java.security.AccessController;

import java.security.Provider;

public final class JSSEProvider extends Provider {

public JSSEProvider() {

super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");

        AccessController

                .doPrivileged(new java.security.PrivilegedAction<Void>() {

                    public Void run() {

                        put("SSLContext.TLS",

                                "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");

                        put("Alg.Alias.SSLContext.TLSv1", "TLS");

                        put("KeyManagerFactory.X509",

                                "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");

                        put("TrustManagerFactory.X509",

                                "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");

                        return null;

                    }

                });

    }

}



Step: 4:-

    
import android.os.Bundle;
 
import android.app.Activity;
 
import android.util.Log;
 
import android.view.Menu;
 
import android.view.View;
 
import android.widget.Button;
 
import android.widget.Toast;
 
 
 
public class MainActivity extends Activity {
 
Button send;
 
 
 
@Override
 
protected void onCreate(Bundle savedInstanceState) {
 
super.onCreate(savedInstanceState);
 
setContentView(R.layout.activity_main);
 
 
 
        send = (Button) findViewById(R.id.send);
 
        send.setOnClickListener(new View.OnClickListener() {
 
 
 
            public void onClick(View v) {
 
                // TODO Auto-generated method stub
 
                new Thread(new Runnable() {
 
                    public void run() {
 
                        try {
 
                            GMailSender sender = new GMailSender(
 
                                    "ravi.sharma@oodlestechnologies.com",
 
                                    "Can't disclose, enter your password and your email");
 
 
 
                            sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");
 
                            sender.sendMail("Test mail", "This mail has been sent from android app along with attachment",
 
                                    "ravi.sharma@oodlestechnologies.com",
 
                                    "ravisharmabpit@gmail.com");
 
                             
 
                             
 
                             
 
                             
 
                        } catch (Exception e) {
 
                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
 
                             
 
                        }
 
                    }
 
                }).start();
 
            }
 
        });
 
 
 
    }
 
 
 
}
- See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

import android.os.Bundle;

import android.app.Activity;

import android.util.Log;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



public class MainActivity extends Activity {

Button send;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);



        send = (Button) findViewById(R.id.send);

        send.setOnClickListener(new View.OnClickListener() {



            public void onClick(View v) {

                // TODO Auto-generated method stub

                new Thread(new Runnable() {

                    public void run() {

                        try {

                            GMailSender sender = new GMailSender(

                                    "chandbecse@gmail.com",

                                    "******************");



                            sender.addAttachment(Environment.getExternalStorageDirectory().getPath()+"/image.jpg");

                            sender.sendMail("Test mail", "This mail has been sent from android app along with attachment",

                                    "chandbecse@gmail.com",

                                    "chandbecse@gmail.com");

                          
                            

                            

                        } catch (Exception e) {

                            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
                        }

                    }

                }).start();

            }

        });

    }


}



This class uses GMailSender class to set the sender email id, password.

using addAttachment method we specify path of file to be attached.

sendMail has four parameters namely subject, body text, senders name, recipients.

Add appropriate file path depending on device and a valid one.




Add Android manifest.xml


<uses-permission android:name="android.permission.INTERNET" /> - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
<uses-permission android:name="android.permission.INTERNET" /> - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
<uses-permission android:name="android.permission.INTERNET" />


Add Jar for mail

jar file


Image








                                                        Thank you







<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 
 
    android:layout_width="match_parent"
 
    android:layout_height="match_parent"
 
    tools:context=".MainActivity"
 
    android:background="@drawable/bg">
 
 
    <Button
 
        android:id="@+id/send"
 
        android:layout_width="150dp"
 
        android:layout_height="70dp"
 
        android:layout_centerInParent="true"
 
        android:background="@drawable/buttonclickcolor"
 
        android:text="Send Mail" />
 
 
 
</RelativeLayout>
- See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf
Sending mail is one key feature in android and an easy one as well.

You may send mail using Intent as well but that requires user interface.

So, this blog will be useful to those who want to send mail in android as a background task without letting the user know. - See more at: http://www.oodlestechnologies.com/blogs/Send-Mail-in-Android-without-Using-Intent#sthash.eUXWfjLg.dpuf

No comments:

Post a Comment