1

I have this simple code with another jar library to enable me to send email without going to other mailing apps.

 public class claimrewardemail extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.successful);

    final String username = "myname@gmail.com"; 
    final String password = "mypassword"; 



    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.port", "587");

                Session session = Session.getInstance(props,
                        new javax.mail.Authenticator() {
                            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                                return new javax.mail.PasswordAuthentication(
                                        username, password);
                            }
                        });
                // TODO Auto-generated method stub
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("from-email@gmail.com"));
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse("youremail@gmail.com")); 
                message.setSubject("email");
                message.setText("HI,"
                        + "\n\n great");

                Transport.send(message);
                System.out.println("Done");


            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    }).start();

  }
 }

This code above help me send mail directly with hard-coded email, title, and message,now I want to add attachment part which I can access my file in the phone and add in a button which I can send attachment along with this mail. Anyone can help me?

Confuser
  • 53
  • 1
  • 9
  • http://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html – Chirag Jain Oct 31 '14 at 06:25
  • Refer this: http://stackoverflow.com/questions/4149265/sending-an-email-with-an-attachment-from-an-application – Krupa Patel Oct 31 '14 at 06:26
  • @ChiragJain, This is sending externally, I tried it before. – Confuser Oct 31 '14 at 06:59
  • possible duplicate of [Sending Email in Android using JavaMail API without using the default/built-in app](http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a) – dodgy_coder Oct 31 '14 at 07:51
  • @dodgy_coder, I have the solution of send mail directly, but not attaching email together. :) – Confuser Oct 31 '14 at 12:25
  • @Confuser did you see one of the answers to that question regarding sending an attachment? ... http://stackoverflow.com/a/5787716/507950 ... that might help you out. – dodgy_coder Oct 31 '14 at 12:54
  • yes, @dodgy_coder, I saw this too, and I tried it, unfortunately, I can choose file but couldn't attach and send together with my email. can u help me check with my code? I wanted to post a question, but I have to wait for another hour to do that. – Confuser Oct 31 '14 at 12:59
  • @Confuser, I'd recommend waiting 1 hr then posting a new question with the entire contents of what you've got now because it sounds like you have all the ingredients of a solution now, but you need new advice on the way to structure your code. – dodgy_coder Oct 31 '14 at 13:02
  • Ok, @dodgy_coder, I will wait for another 1 hour then post it, it's frustrated to get stuck in this, hopefully u could help me out. T.T – Confuser Oct 31 '14 at 13:17
  • @Confuser, no worries - in your new question, add as much information as possible about what you want to do - the better your question, the more likely you'll get a good answer. – dodgy_coder Oct 31 '14 at 13:24
  • @dodgy_coder, seems like no need to be exact 90 minutes, I already posted the question based on it. Can you help me with it?http://stackoverflow.com/questions/26676309/couldnt-attach-file-to-send-email-directly-using-afilechooser I'm having a tough time in this. :( – Confuser Oct 31 '14 at 13:55

2 Answers2

5

Try this:

    String filename = "example_filename";
    Multipart _multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename);

    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
    message.setContent(_multipart);

EDIT:

When you include aFileChooser library, you should create two buttons in your layout of the activity ("Send an email" and "Choose a file"), then in your activity:

private Button sendEmail;
private Button chooseFileButton;
private String filename;
private static final int REQUEST_CHOOSER = 1234;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sendEmail = (Button) findViewById(R.id.send_email_button_id);
    sendEmail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                    Properties props = new Properties();
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.starttls.enable", "true");
                    props.put("mail.smtp.host", "smtp.gmail.com");
                    props.put("mail.smtp.port", "587");

                    Session session = Session.getInstance(props,
                        new javax.mail.Authenticator() {
                            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                                return new javax.mail.PasswordAuthentication(
                                    username, password);
                        }
                    });
                    // TODO Auto-generated method stub
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress("from-email@gmail.com"));
                    message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse("youremail@gmail.com")); 
                    message.setSubject("email");
                    message.setText("HI,"
                        + "\n\n great");
                    if (!"".equals(filename)) {
                        Multipart _multipart = new MimeMultipart();
                        BodyPart messageBodyPart = new MimeBodyPart(); 
                        DataSource source = new FileDataSource(filename);

                        messageBodyPart.setDataHandler(new DataHandler(source)); 
                        messageBodyPart.setFileName(filename); 

                        _multipart.addBodyPart(messageBodyPart); 
                        message.setContent(_multipart);
                    }
                    Transport.send(message);
                    System.out.println("Done");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}).start();
        }
    });

    chooseFileButton = (Button) findViewById(R.id.choose_file_button_id);
    chooseFileButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              // Create the ACTION_GET_CONTENT Intent
              Intent getContentIntent = FileUtils.createGetContentIntent();

              Intent intent = Intent.createChooser(getContentIntent, "Select a file");
              startActivityForResult(intent, REQUEST_CHOOSER);
          }
    });
}

After that add onActivityResult method, where you can get selected filename:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_CHOOSER:   
            if (resultCode == RESULT_OK) {

                final Uri uri = data.getData();

                // Get the File path from the Uri
                filename = FileUtils.getPath(this, uri);
            }
            break;
    }
}

Don't forget to add FileChooserActivity to your AndroidManifest.xml:

<activity
    android:name="com.ipaulpro.afilechooser.FileChooserActivity"
    android:icon="@drawable/ic_launcher"
    android:enabled="true"
    android:exported="true"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.GET_CONTENT" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.OPENABLE" />

        <data android:mimeType="*/*" />
    </intent-filter>
</activity>

After that you can send an email, by click on the "Send" button;

romtsn
  • 11,704
  • 2
  • 31
  • 49
  • Hi @romadja, where should I put this file in? I need to assign a new button right, and enable this code to run. – Confuser Oct 31 '14 at 06:56
  • Yeah sure, this filename is filename of the file that you want to send, you need to add button, and in it's onclick listener open file chooser, see this link if you want to know how to pick file in Android http://stackoverflow.com/a/7857102/3225458. – romtsn Oct 31 '14 at 07:00
  • I see, so meaning that I will have to include the aFileChooser ( https://github.com/iPaulPro/aFileChooser ) in my app, and using a button to link with the onclick listener? – Confuser Oct 31 '14 at 07:06
  • Yes, include aFileChooser, then add button to your layout, and then setOnClickListener to the button, and in that listener do something like this: `Intent getContentIntent = FileUtils.createGetContentIntent(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); startActivityForResult(intent, REQUEST_CHOOSER);` – romtsn Oct 31 '14 at 07:09
  • in `onActivityResult` you will get the filename, and then you can attach file using my code. – romtsn Oct 31 '14 at 07:10
  • Great, let me try this out and if I can do it I accept this answer. :) – Confuser Oct 31 '14 at 07:23
  • Hi @Romadja, I added the afilechooser and added the button with the intent code u given. What is REQUEST_CHOOSER and do I need to declare it? Can I show u the code? – Confuser Oct 31 '14 at 08:45
  • This are my codes,https://www.dropbox.com/sh/ghvdy23gslw6hqz/AABT00GVeLPsKT55GA60Gxl-a?dl=0 – Confuser Oct 31 '14 at 08:55
  • See `Usage` section of the file chooser on the github. It completely explains what should you do – romtsn Oct 31 '14 at 09:03
  • I put the file in already, and the code u give me above, where should I put into my code? – Confuser Oct 31 '14 at 12:24
  • 1
    need to add javax dependency compile 'javax.mail:javax.mail-api:1.5.3' – Brijesh Kumar Mar 04 '17 at 08:09
0

yes it is possible have you add mail.jar and activation.jar files in code please search one button i think u might me know that not normal button when we click on that open new window for selection file that in your local disk and after selecting that you only need to assign that to path in code so email can send with attachment.

Aniket
  • 173
  • 12
  • Yes, it's working with the mail.jar and activation.jar already, but here for the attachment. I'm not sure what code I can type in to do the attachment. confused @@. – Confuser Oct 31 '14 at 06:54
  • have u referred example email with attachment there are lot of example please refereed example and let me know – Aniket Oct 31 '14 at 07:43
  • Yeah, I refer to what @romadja solution above, hopefully it can help. Can you help me check my code if there's any problem? – Confuser Oct 31 '14 at 08:42
  • I refer from here my friend, http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/ – Confuser Oct 31 '14 at 08:49