web-dev-qa-db-fra.com

Envoi de courrier sous Android sans intention via SMTP

Bonjour, je développe une application Android qui enverra un courrier électronique en cliquant sur un bouton. Le code a fonctionné au début, mais pour une raison quelconque, il ne fonctionne pas maintenant. Quelqu'un pourrait-il m'aider, s'il vous plaît, avec ceci? [email protected] est le destinataire . [email protected] est l'expéditeur. J'ai codé en dur le sujet et le corps du courrier.

package com.example.clc_construction;
import Java.io.File;
import Java.io.UnsupportedEncodingException;
import Java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import Android.app.Activity;
import Android.app.ProgressDialog;  
import Android.content.Intent;
import Android.graphics.Bitmap;
import Android.os.AsyncTask;
import Android.os.Bundle;
import Android.os.Environment;


public class Email extends Activity
{
public String jobNo;
public String teamNo;
private static final String username = "[email protected]";
private static final String password = "000000";
private static final String emailid = "[email protected]";
private static final String subject = "Photo";
private static final String message = "Hello";
private Multipart multipart = new MimeMultipart();
private MimeBodyPart messageBodyPart = new MimeBodyPart();
public File mediaFile;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_screen);
    Intent intent = getIntent();
    jobNo = intent.getStringExtra("Job_No");
    teamNo = intent.getStringExtra("Team_No"); 
    sendMail(emailid,subject,message);

}
private void sendMail(String email, String subject, String messageBody)
 {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        }
        catch (AddressException e)
        {
            e.printStackTrace();
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }


private Session createSessionObject()
{
    Properties properties = new Properties();
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.Host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");

    return Session.getInstance(properties, new javax.mail.Authenticator()
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    });
}

private Message createMessage(String email, String subject, String messageBody, Session session) throws 

MessagingException, UnsupportedEncodingException
{
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("[email protected]", "Naveed Qureshi"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
    message.setSubject(subject);
    message.setText(messageBody);
    return message;
}



public class SendMailTask extends AsyncTask<Message, Void, Void>
{
    private ProgressDialog progressDialog;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(Email.this, "Please wait", "Sending mail", true, false);
    }

    @Override
    protected void onPostExecute(Void aVoid)
    {
        super.onPostExecute(aVoid);
        progressDialog.dismiss();
    }

    protected Void doInBackground(javax.mail.Message... messages)
    {
        try
        {
            Transport.send(messages[0]);
        } catch (MessagingException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
}
12
Naveed

Mettez dans votre fichier manifeste,

<uses-permission Android:name="Android.permission.ACCESS_NETWORK_STATE" />

vérifiez si vous avez une connexion internet,

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

et enfin utiliser ce code pour envoyer un email

final String username = "[email protected]";
final String password = "password";

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 PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
  });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();

        messageBodyPart = new MimeBodyPart();
        String file = "path of file to be attached";
        String fileName = "attachmentName"
        DataSource source = new FileDataSource(file);
        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);
    }
15
João Marcos

Puisque vous avez dit que cela fonctionnait auparavant, votre application devrait déjà disposer d'une autorisation Internet et des autres autorisations nécessaires.

  1. Vérifiez si le téléphone actuel que vous essayez a le service de données/Internet mobile approprié
  2. Si vous êtes connecté via Wi-Fi, vérifiez si une nouvelle restriction de pare-feu n'autorise pas l'envoi du courrier.
0
Nishanthi Grashia

comme indiqué ci-dessous, définir une référence à partir de Ici

repositories { 
     jcenter()
     maven {
         url "https://maven.Java.net/content/groups/public/"
     }
}

dependencies {
     compile 'com.Sun.mail:Android-mail:1.5.5'
     compile 'com.Sun.mail:Android-activation:1.5.5'
}

Android {
   packagingOptions {
       pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
   }
}

Ajouter cette tâche asynchrone pour envoyer du courrier 

 public class sendemail extends AsyncTask<String, Integer, Integer> {

    ProgressDialog progressDialog;
    private StringBuilder all_email;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(GetuserActivity.this);
        progressDialog.setMessage("Uploading, please wait...");
        progressDialog.show();
        if (selecteduser_arr != null) {
            all_email = new StringBuilder();
            for (int i = 0; i < selecteduser_arr.size(); i++) {
                if (i == 0) {
                    all_email.append(selecteduser_arr.get(i));
                } else {
                    String temp = "," + selecteduser_arr.get(i);
                    all_email.append(temp);
                }
            }
        }
    }

    @Override
    protected Integer doInBackground(String... strings) {

        Properties props = new Properties();
        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");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("enterhereyouremail", "enterherepassword");
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("enterhereyouremail"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected],[email protected]"));
            message.setSubject("Testing Subject");
            message.setText("Dear Mail Crawler," +
                    "\n\n No spam to my email, please!");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        progressDialog.dismiss();
    }
}
0
Manthan Patel

Essayez d'utiliser le port 465

 private Session createSessionObject()
    {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.smtp.Host", "smtp.gmail.com");
        properties.setProperty("mail.smtp.port", "465");

        return Session.getInstance(properties, new javax.mail.Authenticator()
        {
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(username, password);
            }
        });
    }
0
Ludger