I have an app created and an option is to send a form in background using javamail, the problem is that when adding an image, the application acts as if it sent the mail correctly but in the Gmail tray I do not receive anything . However, if I send the same email but without adding an attached image if I receive the email perfectly. I have looked in a thousand places but I can not find the solution to the problem. I attach the complete code.
public class Correo extends AppCompatActivity implements LocationListener{
//Declaring EditText
private EditText editTextSubject;
private EditText editTextMessage;
private EditText editTextNombre;
private EditText editTextApellidos;
private EditText editTextTelefono;
/*public static final String Nombre = "NomKey";
public static final String Apellidos = "ApKey";
public static final String Asunto = "AsKey";
public static final String Mensaje = "MenKey";
public static final String Telefono = "TelKey";
public static final String mypreference = "mypref";*/
Button btnTackPic;
ImageView ivThumbnailPhoto;
Bitmap bitMap;
static int TAKE_PICTURE = 1;
private static final int PICK_IMAGE = 100;
Uri imageUri;
Button btngal;
String rutaimg;
LocationManager locationManager;
Location location;
//Send button
private Button buttonSend;
Button btnUbicacion;
String ubicacion;
double latitud = 0;
double longitud = 0;
EditText editubi;
Bitmap bitimg;
File imagefile;
BodyPart adjunto = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.correo);
//Initializing the views
editTextSubject = (EditText) findViewById(R.id.editTextSubject);
editTextMessage = (EditText) findViewById(R.id.editTextMessage);
editTextNombre = (EditText) findViewById(R.id.editTextNombre);
editTextApellidos = (EditText) findViewById(R.id.editTextApellidos);
editTextTelefono = (EditText) findViewById(R.id.editTextTelefono);
editubi = (EditText) findViewById(R.id.editubi);
buttonSend = (Button) findViewById(R.id.buttonSend);
btnUbicacion = (Button) findViewById(R.id.btnUbicacion);
//Adding click listener
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendEmail();
}
});
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
btnUbicacion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getLocation();
}
});;
btnTackPic = (Button) findViewById(R.id.btnTakePic);
ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);
// add onclick listener to the button
btnTackPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
});
btngal = (Button) findViewById(R.id.btngal) ;
btngal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openGallery();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent!=null){
// get bundle
bitMap = (Bitmap) intent.getExtras().get("data");
ivThumbnailPhoto.setImageBitmap(bitMap);
}
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
imageUri = intent.getData();
imagefile = new File(getRealPathFromURI(imageUri));
ivThumbnailPhoto.setImageURI(imageUri);
try {
bitimg = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void openGallery(){
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(gallery, PICK_IMAGE);
}
private void sendEmail() {
//Getting content for email
String email = "**********@gmail.com";
String subject = editTextSubject.getText().toString().trim();
String message = editTextMessage.getText().toString().trim();
String nombre = editTextNombre.getText().toString().trim();
String apellidos = editTextApellidos.getText().toString().trim();
String telefono = editTextTelefono.getText().toString().trim();
String ubiman = editubi.getText().toString().trim();
String msg = "Nombre: " + nombre + " " + apellidos + "\n" + "\n" + "Teléfono: " + telefono + "\n" + "\n" + "Asunto: " + subject + "\n" + "\n" + "Incidencia: " + message + "\n" + "\n" + "Ubicación manual : " + ubiman + "\n" + "\n" + "Ubicación GPS: " + ubicacion + "\n" + "\n" ;
/*if (subject.equals("") || message.equals("") || nombre.equals("") || apellidos.equals("") || telefono.equals("")) {
Toast.makeText(this, "Por favor, rellene todos los campos marcados con asterisco", Toast.LENGTH_SHORT).show();
}
else{*/
//Creating SendMail object
SendMail sm = new SendMail(this, email, subject, msg, imagefile);
//Executing sendmail to send email
sm.execute();
editTextMessage.setText("");
editTextSubject.setText("");
editTextTelefono.setText("");
editTextApellidos.setText("");
editTextNombre.setText("");
//}
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
latitud = location.getLatitude();
longitud = location.getLongitude();
ubicacion = "https://maps.google.com?q=" + latitud + "," + longitud;
if (latitud != 0 || longitud != 0) {
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list = geocoder.getFromLocation(
latitud, longitud, 1);
if (!list.isEmpty()) {
Address DirCalle = list.get(0);
editubi.setText(DirCalle.getAddressLine(0));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(Correo.this, "Active el GPS y el Internet", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: //hago un case por si en un futuro agrego mas opciones
Log.i("ActionBar", "Atrás!");
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The image file is sent to the SendMail class, where it is received perfectly:
public class SendMail 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 message;
//private MimeMultipart Adjunto = new MimeMultipart();
private File imagefile;
//private BodyPart adjunto = new MimeBodyPart();
//private BodyPart texto = new MimeBodyPart();
//Progressdialog to show while sending email
private ProgressDialog progressDialog;
private Intent intent;
//Class Constructor
public SendMail(Context context, String email, String subject, String message, File imagefile){
//Initializing variables
this.context = context;
this.email = email;
this.subject = subject;
this.message = message;
this.imagefile = imagefile;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
progressDialog = ProgressDialog.show(context,"Enviando incidencia","Espere...",false,false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
progressDialog.dismiss();
//Showing a success message
Toast.makeText(context,"Incidencia enviada",Toast.LENGTH_LONG).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.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.user", "***********@gmail.com");
props.setProperty("mail.smtp.auth", "true");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Config.EMAIL, Config.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
MimeMultipart multipart = new MimeMultipart();
//Setting sender address
mm.setFrom(new InternetAddress(Config.EMAIL));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
mm.setText(message);
MimeBodyPart at = new MimeBodyPart();
at.setDisposition(MimeBodyPart.ATTACHMENT);
at.attachFile(imagefile);
at.setFileName("incidencia.jpg");
//multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(at);
//Adding message
mm.setContent(multipart);
Transport t = session.getTransport("smtp");
t.connect(Config.EMAIL,Config.PASSWORD);
t.sendMessage(mm,mm.getAllRecipients());
t.close();
//Sending email
//Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}