I want to add an attachment (be it a link,image, video or anything else) along with the text that I send through email. Till now, I can only send the plain text as email. How do I add an attachment along with it?
Here's my code for sending the email process in the worker thread:
public class GMailSender extends AsyncTask<Void,Void,Void> {
//Declaring Variables
private Context context;
private Session session;
//Information to send email
private String email;
private String subject;
private String msg;
//Progressdialog to show while sending email
//Class Constructor
public GMailSender(Context context, String email, String subject, String msg){
if (rb1 != null && rad.isChecked()){
message=s1;
}else if(rb1 != null && rad1.isChecked())
{
message=item;
}
//Initializing variables
this.context = context;
this.email = s4;
this.subject = s3;
this.msg = message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
// progressDialog = ProgressDialog.show(context,"Sending message","Please wait...",false,false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
//Showing a success message
Toast.makeText(context,"Message Sent",Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(Void... params) {
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Smscreator.EMAIL, Smscreator.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
//Setting sender address
mm.setFrom(new InternetAddress(Smscreator.EMAIL));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(msg);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
Here's the code for sending the mail :
GMailSender sm = new GMailSender(context, s4, s3, message);
sm.execute();
Toast.makeText(context, "Email sent :)",
Toast.LENGTH_SHORT).show();
Edit : As suggested, I've looked into [Sending Email in Android using JavaMail API without using the default/built-in app. But nothing is written about adding an attachment in the solutions.