Javamail не работает, но я не могу найти проблему. (Ошибка аутентификации) - PullRequest
0 голосов
/ 18 мая 2019

Я пытаюсь отправить строку по электронной почте мне. Я использую javamail. Однако, когда я нажму кнопку «Отправить» в моем приложении, он скажет, что приложение было отправлено, но я не получу никакой почты. Google впервые отправляет оповещение из-за внешних разрешений приложения. После изменения разрешений ничего не происходит. Я до сих пор не получаю никаких писем.

При отладке кажется, что аутентификация не удалась.

У меня есть 3 действия: Main, Config для изменения Sender и SendMail для фактического синтаксиса. Я очень ценю помощь или если кто-то может сказать лучший способ сделать это.

Вот отладка:

V / ViewRootImpl: чертеж завершен: отправка сообщения

W / SplitWindow: обновить фокус ...

E / Editor: hideClipTrayIfNeeded () TextView сфокусирован !! hideClipTray ()

W / System.err: javax.mail.AuthenticationFailedException

W / System.err: at javax.mail.Service.connect (Service.java:319)

    at javax.mail.Service.connect(Service.java:169)

    at javax.mail.Service.connect(Service.java:118)

    at javax.mail.Transport.send0(Transport.java:188)

    at javax.mail.Transport.send(Transport.java:118)

    at com.example.m2.SendMail.doInBackground(SendMail.java:96)

    at com.example.m2.SendMail.doInBackground(SendMail.java:21)

    at android.os.AsyncTask$2.call(AsyncTask.java:295)

    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    at java.lang.Thread.run(Thread.java:818)

W / SplitWindow: обновить фокус ...

Основная деятельность:

открытый класс MainActivity расширяет AppCompatActivity, реализует View.OnClickListener {

private Button exitBtn;
private Button sendButton;
private EditText wText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    exitBtn = (Button)findViewById(R.id.exitButton);
    exitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            moveTaskToBack(true);
            android.os.Process.killProcess(Process.myPid());
            System.exit(1);
        }
    });

    sendButton = (Button)findViewById(R.id.sendButton);
    wText      = (EditText)findViewById(R.id.wInput);

    sendButton.setOnClickListener(this);
}

private void sendEmail() {
    //Getting content for email
    String email = "(mytargetmail)";
    String subject = wText.getText().toString().trim();
    String message = "Mamas neuer Wunsch";

    //Creating SendMail object
    SendMail sm = new SendMail(this, email, subject, message);

    //Executing sendmail to send email
    sm.execute();

}`enter code here`

@Override
public void onClick(View v) {
    sendEmail();
}

}

Config:

public class Config {
public static final String EMAIL ="my mail";
public static final String PASSWORD ="and password";

}

SendEmail:

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;

//Progressdialog to show while sending email
private ProgressDialog progressDialog;

//Class Constructor
public SendMail(Context context, String email, String subject, String message){
    //Initializing variables
    this.context = context;
    this.email = email;
    this.subject = subject;
    this.message = 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
    progressDialog.dismiss();
    //Showing a success message
    Toast.makeText(context,"Message Sent",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.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(Config.EMAIL, Config.PASSWORD);
                }
            });

    try {
        //Creating MimeMessage object
        MimeMessage mm = new MimeMessage(session);

        //Setting sender address
        mm.setFrom(new InternetAddress(Config.EMAIL));
        //Adding receiver
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        //Adding subject
        mm.setSubject(subject);
        //Adding message
        mm.setText(message);

        //Sending email
        Transport.send(mm);

    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return null;
}

}

...