Wysyłanie wiadomości e-mail w systemie Android za pomocą JavaMail API bez użycia domyślnej / wbudowanej aplikacji

Próbuję stworzyć aplikację wysyłającą pocztę na Androida.

Jeśli użyję:

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

To uruchomi wbudowaną aplikację na Androida; Próbuję wysłać pocztę na przycisk Kliknij bezpośrednio Bez za pomocą tej aplikacji.

Author: Alireza Sabahi, 2010-01-07

25 answers

Wysyłanie wiadomości e-mail w systemie Android za pomocą JavaMail API przy użyciu uwierzytelniania Gmail.

Kroki tworzenia przykładowego projektu:

MailSenderActivity.java:

public class MailSenderActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button send = (Button) this.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                try {   
                    GMailSender sender = new GMailSender("[email protected]", "password");
                    sender.sendMail("This is Subject",   
                            "This is Body",   
                            "[email protected]",   
                            "[email protected]");   
                } catch (Exception e) {   
                    Log.e("SendMail", e.getMessage(), e);   
                } 
                
            }
        });
        
    }
}

GMailSender.java:

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   
  
    static {   
        Security.addProvider(new com.provider.JSSEProvider());   
    }  
  
    public GMailSender(String user, String password) {   
        this.user = user;   
        this.password = password;   
  
        Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.port", "465");   
        props.put("mail.smtp.socketFactory.port", "465");   
        props.put("mail.smtp.socketFactory.class",   
                "javax.net.ssl.SSLSocketFactory");   
        props.put("mail.smtp.socketFactory.fallback", "false");   
        props.setProperty("mail.smtp.quitwait", "false");   
  
        session = Session.getDefaultInstance(props, this);   
    }   
  
    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   
  
    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(sender));   
        message.setSubject(subject);   
        message.setDataHandler(handler);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){
            
        }
    }   
  
    public class ByteArrayDataSource implements DataSource {   
        private byte[] data;   
        private String type;   
  
        public ByteArrayDataSource(byte[] data, String type) {   
            super();   
            this.data = data;   
            this.type = type;   
        }   
  
        public ByteArrayDataSource(byte[] data) {   
            super();   
            this.data = data;   
        }   
  
        public void setType(String type) {   
            this.type = type;   
        }   
  
        public String getContentType() {   
            if (type == null)   
                return "application/octet-stream";   
            else  
                return type;   
        }   
  
        public InputStream getInputStream() throws IOException {   
            return new ByteArrayInputStream(data);   
        }   
  
        public String getName() {   
            return "ByteArrayDataSource";   
        }   
  
        public OutputStream getOutputStream() throws IOException {   
            throw new IOException("Not Supported");   
        }   
    }   
}  

JSSEProvider.java:

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Alexander Y. Kleymenov
 * @version $Revision$
 */


import java.security.AccessController;
import java.security.Provider;

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}

Dodaj 3 słoiki Znalezione w poniższym linku do swojego projektu Android

Kliknij tutaj - Jak dodawać zewnętrzne słoiki

I nie zapomnij dodać tej linii w manifeście:

<uses-permission android:name="android.permission.INTERNET" />

Wystarczy kliknąć poniższy link, aby zmienić dostęp do konta dla mniej bezpiecznych aplikacji]} https://www.google.com/settings/security/lesssecureapps

Uruchom projekt i sprawdź konto pocztowe odbiorcy. Zdrowie!

P. S. i nie zapominaj, że nie możesz wykonywać operacji sieciowych z żadnej aktywności w Androidzie. Dlatego zaleca się stosowanie AsyncTask lub IntentService w celu uniknięcia wyjątek network on main thread.

Pliki Jar: https://code.google.com/archive/p/javamail-android/

 769
Author: Vinayak Bevinakatti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Dziękuję za cenne informacje. Kod działa dobrze. Mogę dodać załącznik również poprzez dodanie następującego kodu.

private Multipart _multipart; 
_multipart = new MimeMultipart(); 

public void addAttachment(String filename,String subject) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 
    _multipart.addBodyPart(messageBodyPart);

    BodyPart messageBodyPart2 = new MimeBodyPart(); 
    messageBodyPart2.setText(subject); 

    _multipart.addBodyPart(messageBodyPart2); 
} 



message.setContent(_multipart);
 73
Author: ashok reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-11 11:37:12

Nie można połączyć się z hostem SMTP: smtp.gmail.com, port: 465

Dodaj ten wiersz w manifeście:

<uses-permission android:name="android.permission.INTERNET" />
 55
Author: ManuV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-17 13:25:22

Możesz użyć JavaMail API do obsługi zadań poczty e-mail. JavaMail API jest dostępny w pakiecie JavaEE, a jego jar jest dostępny do pobrania. Niestety nie można go używać bezpośrednio w aplikacji na Androida, ponieważ używa komponentów AWT, które są całkowicie niekompatybilne w Androidzie.

Możesz znaleźć Port Androida dla JavaMail w następującej lokalizacji: http://code.google.com/p/javamail-android/

Dodaj słoiki do aplikacji i użyj metody SMTP

 40
Author: Kshitij Aggarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-08 11:21:30

Aby pomóc tym, którzy uzyskują wyjątek sieci w głównym wątku z celem SDK >9. Jest to użycie powyższego kodu droopie, ale będzie działać podobnie dla każdego.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

android.os.NetworkOnMainThreadException

Możesz użyć AsyncTask jak poniżej

public void onClickMail(View view) {
    new SendEmailAsyncTask().execute();
}

class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
    Mail m = new Mail("[email protected]", "my password");

    public SendEmailAsyncTask() {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
        String[] toArr = { "to [email protected]"};
        m.setTo(toArr);
        m.setFrom("from [email protected]");
        m.setSubject("Email from Android");
        m.setBody("body.");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
        try {
            m.send();
            return true;
        } catch (AuthenticationFailedException e) {
            Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
            e.printStackTrace();
            return false;
        } catch (MessagingException e) {
            Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null) + "failed");
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 30
Author: Ryan Heitner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-15 05:03:27

100% kod roboczy z demo możesz również wysłać wiele e-maili za pomocą tej odpowiedzi.

Pobierz projekt proszę.

Krok 1: Pobierz pocztę, aktywację, dodatkowe pliki jar i dodaj do folderu project libs W android studio. Dodałem zrzut ekranu patrz poniżej link do pobrania

libs dodaj

Zaloguj się za pomocą Gmaila (za pomocą poczty from) i włącz przycisk przełączania LINK

Większość ludzi zapomina o tym kroku, mam nadzieję, że nie.

Krok 2: Po zakończeniu tego procesu. Skopiuj i przekaż te zajęcia do swojego projektu.

GMail.java

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GMail {

    final String emailPort = "587";// gmail's smtp port
    final String smtpAuth = "true";
    final String starttls = "true";
    final String emailHost = "smtp.gmail.com";


    String fromEmail;
    String fromPassword;
    List<String> toEmailList;
    String emailSubject;
    String emailBody;

    Properties emailProperties;
    Session mailSession;
    MimeMessage emailMessage;

    public GMail() {

    }

    public GMail(String fromEmail, String fromPassword,
            List<String> toEmailList, String emailSubject, String emailBody) {
        this.fromEmail = fromEmail;
        this.fromPassword = fromPassword;
        this.toEmailList = toEmailList;
        this.emailSubject = emailSubject;
        this.emailBody = emailBody;

        emailProperties = System.getProperties();
        emailProperties.put("mail.smtp.port", emailPort);
        emailProperties.put("mail.smtp.auth", smtpAuth);
        emailProperties.put("mail.smtp.starttls.enable", starttls);
        Log.i("GMail", "Mail server properties set.");
    }

    public MimeMessage createEmailMessage() throws AddressException,
            MessagingException, UnsupportedEncodingException {

        mailSession = Session.getDefaultInstance(emailProperties, null);
        emailMessage = new MimeMessage(mailSession);

        emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
        for (String toEmail : toEmailList) {
            Log.i("GMail", "toEmail: " + toEmail);
            emailMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmail));
        }

        emailMessage.setSubject(emailSubject);
        emailMessage.setContent(emailBody, "text/html");// for a html email
        // emailMessage.setText(emailBody);// for a text email
        Log.i("GMail", "Email Message created.");
        return emailMessage;
    }

    public void sendEmail() throws AddressException, MessagingException {

        Transport transport = mailSession.getTransport("smtp");
        transport.connect(emailHost, fromEmail, fromPassword);
        Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
        transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
        transport.close();
        Log.i("GMail", "Email sent successfully.");
    }

}

Wyślij maila.java

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import java.util.List;

public class SendMailTask extends AsyncTask {

    private ProgressDialog statusDialog;
    private Activity sendMailActivity;

    public SendMailTask(Activity activity) {
        sendMailActivity = activity;

    }

    protected void onPreExecute() {
        statusDialog = new ProgressDialog(sendMailActivity);
        statusDialog.setMessage("Getting ready...");
        statusDialog.setIndeterminate(false);
        statusDialog.setCancelable(false);
        statusDialog.show();
    }

    @Override
    protected Object doInBackground(Object... args) {
        try {
            Log.i("SendMailTask", "About to instantiate GMail...");
            publishProgress("Processing input....");
            GMail androidEmail = new GMail(args[0].toString(),
                    args[1].toString(), (List) args[2], args[3].toString(),
                    args[4].toString());
            publishProgress("Preparing mail message....");
            androidEmail.createEmailMessage();
            publishProgress("Sending email....");
            androidEmail.sendEmail();
            publishProgress("Email Sent.");
            Log.i("SendMailTask", "Mail Sent.");
        } catch (Exception e) {
            publishProgress(e.getMessage());
            Log.e("SendMailTask", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public void onProgressUpdate(Object... values) {
        statusDialog.setMessage(values[0].toString());

    }

    @Override
    public void onPostExecute(Object result) {
        statusDialog.dismiss();
    }

}

Krok 3: Teraz możesz zmienić tę klasę w zależności od potrzeb Możesz również wysłać wiele wiadomości za pomocą tej klasy. dostarczam plik xml i java jedno i drugie.

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="30dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="From Email" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:cursorVisible="true"
        android:editable="true"
        android:ems="10"
        android:enabled="true"
        android:inputType="textEmailAddress"
        android:padding="5dp"
        android:textColor="#000000">

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Password (For from email)" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:ems="10"
        android:inputType="textPassword"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="To Email" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Subject" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:padding="5dp"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Body" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="textMultiLine"
        android:padding="35dp"
        android:textColor="#000000" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Email" />

</LinearLayout>

/ align = "left" / java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Arrays;
import java.util.List;

public class SendMailActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button send = (Button) this.findViewById(R.id.button1);

        send.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Log.i("SendMailActivity", "Send Button Clicked.");

                String fromEmail = ((TextView) findViewById(R.id.editText1))
                        .getText().toString();
                String fromPassword = ((TextView) findViewById(R.id.editText2))
                        .getText().toString();
                String toEmails = ((TextView) findViewById(R.id.editText3))
                        .getText().toString();
                List<String> toEmailList = Arrays.asList(toEmails
                        .split("\\s*,\\s*"));
                Log.i("SendMailActivity", "To List: " + toEmailList);
                String emailSubject = ((TextView) findViewById(R.id.editText4))
                        .getText().toString();
                String emailBody = ((TextView) findViewById(R.id.editText5))
                        .getText().toString();
                new SendMailTask(SendMailActivity.this).execute(fromEmail,
                        fromPassword, toEmailList, emailSubject, emailBody);
            }
        });
    }
}

Uwaga nie zapomnij dodać internet uprawnienia w AndroidManifest.plik xml

<uses-permission android:name="android.permission.INTERNET"/>

Mam nadzieję, że zadziała, jeśli nie, to po prostu skomentuj poniżej.

 30
Author: Arpit Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-10 16:15:05

SMTP

Używanie SMTP jest jednym ze sposobów, a inni już wskazali sposoby, jak to zrobić. Pamiętaj tylko, że podczas tego wykonywania całkowicie omijasz wbudowaną aplikację pocztową i będziesz musiał podać adres serwera SMTP, nazwę użytkownika i hasło dla tego serwera, statycznie w kodzie lub odpytywać go od użytkownika.

HTTP

Inny sposób wiązałby się z prostym skryptem po stronie serwera, takim jak php, który pobiera niektóre parametry URL i używa ich do wyślij maila. W ten sposób wystarczy tylko wykonać żądanie HTTP z urządzenia (łatwo możliwe dzięki wbudowanym bibliotekom) i nie trzeba przechowywać danych logowania SMTP na urządzeniu. Jest to jeszcze jedna indirection w porównaniu do bezpośredniego użycia SMTP, ale ponieważ jest to tak bardzo łatwe do żądania HTTP i wysyłania wiadomości z PHP, może to być nawet prostsze niż bezpośredni sposób.

Aplikacja Pocztowa

Jeśli poczta zostanie wysłana z domyślnego konta pocztowego użytkownika, na którym już się zarejestrował telefon, musiałbyś podejść inaczej. Jeśli masz wystarczająco dużo czasu i doświadczenia, możesz sprawdzić kod źródłowy aplikacji e-mail na Androida, aby sprawdzić, czy oferuje jakiś punkt wejścia do wysyłania poczty bez interakcji użytkownika(Nie wiem, ale może jest taki).

Może nawet znajdziesz sposób na sprawdzenie danych konta użytkowników (aby można było z nich korzystać dla SMTP), choć szczerze wątpię, że jest to możliwe, ponieważ byłoby to ogromne ryzyko bezpieczeństwa, a Android jest zbudowany raczej bezpiecznie.

 24
Author: Lena Schimmel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-08 11:32:12

Oto wersja alt, która również działa dla mnie i ma załączniki (opublikowane już powyżej, ale pełna wersja w przeciwieństwie do linku źródłowego, które ludzie opublikowali, nie mogą go uruchomić, ponieważ brakujące dane)

import java.util.Date; 
import java.util.Properties; 
import javax.activation.CommandMap; 
import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.activation.MailcapCommandMap; 
import javax.mail.BodyPart; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 


public class Mail extends javax.mail.Authenticator { 
  private String _user; 
  private String _pass; 

  private String[] _to; 
  private String _from; 

  private String _port; 
  private String _sport; 

  private String _host; 

  private String _subject; 
  private String _body; 

  private boolean _auth; 

  private boolean _debuggable; 

  private Multipart _multipart; 


  public Mail() { 
    _host = "smtp.gmail.com"; // default smtp server 
    _port = "465"; // default smtp port 
    _sport = "465"; // default socketfactory port 

    _user = ""; // username 
    _pass = ""; // password 
    _from = ""; // email sent from 
    _subject = ""; // email subject 
    _body = ""; // email body 

    _debuggable = false; // debug mode on or off - default off 
    _auth = true; // smtp authentication - default on 

    _multipart = new MimeMultipart(); 

    // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
  } 

  public Mail(String user, String pass) { 
    this(); 

    _user = user; 
    _pass = pass; 
  } 

  public boolean send() throws Exception { 
    Properties props = _setProperties(); 

    if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { 
      Session session = Session.getInstance(props, this); 

      MimeMessage msg = new MimeMessage(session); 

      msg.setFrom(new InternetAddress(_from)); 

      InternetAddress[] addressTo = new InternetAddress[_to.length]; 
      for (int i = 0; i < _to.length; i++) { 
        addressTo[i] = new InternetAddress(_to[i]); 
      } 
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

      msg.setSubject(_subject); 
      msg.setSentDate(new Date()); 

      // setup message body 
      BodyPart messageBodyPart = new MimeBodyPart(); 
      messageBodyPart.setText(_body); 
      _multipart.addBodyPart(messageBodyPart); 

      // Put parts in message 
      msg.setContent(_multipart); 

      // send email 
      Transport.send(msg); 

      return true; 
    } else { 
      return false; 
    } 
  } 

  public void addAttachment(String filename) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
    messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

    _multipart.addBodyPart(messageBodyPart); 
  } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication(_user, _pass); 
  } 

  private Properties _setProperties() { 
    Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

    if(_debuggable) { 
      props.put("mail.debug", "true"); 
    } 

    if(_auth) { 
      props.put("mail.smtp.auth", "true"); 
    } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
  } 

  // the getters and setters 
  public String getBody() { 
    return _body; 
  } 

  public void setBody(String _body) { 
    this._body = _body; 
  }

  public void setTo(String[] toArr) {
      // TODO Auto-generated method stub
      this._to=toArr;
  }

  public void setFrom(String string) {
      // TODO Auto-generated method stub
      this._from=string;
  }

  public void setSubject(String string) {
      // TODO Auto-generated method stub
      this._subject=string;
  }  

  // more of the getters and setters ….. 
}

I nazwać to aktywnością...

@Override 
public void onCreate(Bundle icicle) { 
  super.onCreate(icicle); 
  setContentView(R.layout.main); 

  Button addImage = (Button) findViewById(R.id.send_email); 
  addImage.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
      Mail m = new Mail("[email protected]", "password"); 

      String[] toArr = {"[email protected]", "[email protected]"}; 
      m.setTo(toArr); 
      m.setFrom("[email protected]"); 
      m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device."); 
      m.setBody("Email body."); 

      try { 
        m.addAttachment("/sdcard/filelocation"); 

        if(m.send()) { 
          Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show(); 
        } else { 
          Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show(); 
        } 
      } catch(Exception e) { 
        //Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show(); 
        Log.e("MailApp", "Could not send email", e); 
      } 
    } 
  }); 
} 
 23
Author: droopie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-19 03:55:14
Gmailbackground jest małą biblioteką do wysyłania wiadomości e-mail w tle bez interakcji z użytkownikiem:]}

Użycie:

    BackgroundMail.newBuilder(this)
            .withUsername("[email protected]")
            .withPassword("password12345")
            .withMailto("[email protected]")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();

Konfiguracja:

repositories {
    // ...
    maven { url "https://jitpack.io" }
 }
 dependencies {
            compile 'com.github.yesidlazaro:GmailBackground:1.2.0'
    }

Uprawnienia:

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

Również dla załączników, musisz ustawić uprawnienia READ_EXTERNAL_STORAGE:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Źródło

(sam przetestowałem)

 16
Author: S.R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-17 18:35:06

Słowo ostrzeżenia jeśli używasz "smtp.gmail.com" jako domyślny serwer smtp.

Google zmusi cię do częstej zmiany hasła do połączonego konta e-mail ze względu na ich nadgorliwą politykę "podejrzanej aktywności". Zasadniczo traktuje powtarzające się wnioski smtp z różnych krajów w krótkim czasie jako"podejrzaną aktywność". Jak zakładają, użytkownik (posiadacz konta e-mail) może przebywać tylko w jednym kraju na raz.

Gdy systemy google wykryją "podejrzaną aktywność" to zapobiegaj dalszym e-mailom, dopóki nie zmienisz hasła. Ponieważ będziesz musiał zakodować hasło do aplikacji, musisz ponownie zwolnić aplikację za każdym razem, gdy tak się stanie, nie idealnie. Zdarzyło mi się to 3 razy w tygodniu, nawet zapisałem hasło na innym serwerze i dynamicznie pobierałem hasło za każdym razem, gdy google zmusiło mnie do zmiany.

Więc polecam korzystanie z jednego z wielu darmowych dostawców smtp zamiast "smtp.gmail.com" aby uniknąć tego problemu bezpieczeństwa. Użyj tego samego kodu, ale zmień "smtp.gmail.com" do nowego hosta przekierowującego smtp.

 15
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 12:26:47

Edit: JavaMail 1.5.5 twierdzi, że obsługuje Androida , więc nie powinieneś potrzebować niczego innego.

Przeportowałem najnowszy JavaMail (1.5.4) na Androida. Jest dostępny w Maven Central, wystarczy dodać następujące build.gradle~~

compile 'eu.ocathain.com.sun.mail:javax.mail:1.5.4'

Możesz następnie postępować zgodnie z oficjalnym tutorialem .

Kod źródłowy jest dostępny tutaj: https://bitbucket.org/artbristol/javamail-forked-android

 8
Author: artbristol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-28 20:55:48

Znalazłem krótszą alternatywę dla innych, którzy potrzebują pomocy. Kod to:

package com.example.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailTLS {

    public static void main(String[] args) {

        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!");

            Transport.send(message);

            System.out.println("Done");

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

Źródło: wysyłanie wiadomości e-mail przez JavaMail API

Mam nadzieję, że to pomoże! Powodzenia!
 7
Author: Shreshth Kharbanda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-12 20:49:41

Za wysłanie wiadomości z załącznikiem..

public class SendAttachment{
                    public static void main(String [] args){ 
             //to address
                    String to="[email protected]";//change accordingly
                    //from address
                    final String user="[email protected]";//change accordingly
                    final String password="password";//change accordingly 
                     MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
                   mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
                  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
                  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
                  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
                  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
                  CommandMap.setDefaultCommandMap(mc); 
                  //1) get the session object   
                  Properties properties = System.getProperties();
                  properties.put("mail.smtp.port", "465"); 
                  properties.put("mail.smtp.host", "smtp.gmail.com");
                    properties.put("mail.smtp.socketFactory.port", "465");
                    properties.put("mail.smtp.socketFactory.class",
                            "javax.net.ssl.SSLSocketFactory");
                    properties.put("mail.smtp.auth", "true");
                    properties.put("mail.smtp.port", "465");

                  Session session = Session.getDefaultInstance(properties,
                   new javax.mail.Authenticator() {
                   protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(user,password);
                   }
                  });

                  //2) compose message   
                  try{ 
                    MimeMessage message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(user));
                    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
                    message.setSubject("Hii"); 
                    //3) create MimeBodyPart object and set your message content    
                    BodyPart messageBodyPart1 = new MimeBodyPart();
                    messageBodyPart1.setText("How is This"); 
                    //4) create new MimeBodyPart object and set DataHandler object to this object    
                    MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //Location of file to be attached
                    String filename = Environment.getExternalStorageDirectory().getPath()+"/R2832.zip";//change accordingly
                    DataSource source = new FileDataSource(filename);
                    messageBodyPart2.setDataHandler(new DataHandler(source));
                    messageBodyPart2.setFileName("Hello"); 
                    //5) create Multipart object and add MimeBodyPart objects to this object    
                    Multipart multipart = new MimeMultipart();
                    multipart.addBodyPart(messageBodyPart1);
                    multipart.addBodyPart(messageBodyPart2); 
                    //6) set the multiplart object to the message object
                    message.setContent(multipart ); 
                    //7) send message 
                    Transport.send(message); 
                   System.out.println("MESSAGE SENT....");
                   }catch (MessagingException ex) {ex.printStackTrace();}
                  }
                }
 5
Author: Rashid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-06 06:10:57

Ci, którzy dostają ClassDefNotFoundError spróbuj przenieść te trzy pliki jar do folderu lib twojego projektu, zadziałało dla mnie!!

 5
Author: Omkar Gokhale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-04 07:32:10

Nie jestem w stanie uruchomić kodu Vinayak B. W końcu rozwiązałem ten problem, wykonując następujące czynności:

1.Using this

2.Zastosowanie AsyncTask.

3.Zmiana kwestii bezpieczeństwa konta Gmail nadawcy.(Zmień na "Włącz") w to

 4
Author: Patriotic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-26 06:34:40

Czy rozważałeś użycie Apache Commons Net ? Od 3.3 wystarczy jeden jar (i można na nim polegać używając gradle lub maven) i gotowe: http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/

 3
Author: Anthony Dahanne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-18 03:28:11

Bez interwencji użytkownika możesz wysłać w następujący sposób:

  1. Wyślij e-mail z klienta apk. Poczta.jar, aktywacja.jar jest wymagany do wysyłania poczty java. Jeśli te słoiki zostaną dodane, może to zwiększyć rozmiar APK.

  2. Alternatywnie możesz użyć usługi internetowej po stronie serwera, która użyje tej samej poczty.słoik i aktywacja.jar, aby wysłać e-mail. Możesz zadzwonić do serwisu internetowego za pomocą asynctask i wysłać e-mail. Poleć ten sam link.

(ale, będziesz musisz znać dane uwierzytelniające konta pocztowego)

 3
Author: Nishanthi Grashia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-30 09:37:30

W przypadku, gdy wymaga się, aby Biblioteka jar była jak najmniejsza, można dołączyć funkcję SMTP/POP3/IMAP oddzielnie, aby uniknąć problemu "zbyt wiele metod w dex".

Możesz wybrać pożądane biblioteki jar z strony javanet , na przykład mailapi.jar + imap.jar umożliwia dostęp do icloud, serwera poczty hotmail w protokole IMAP. (z pomocą dodatkowych.słoik i aktywacja.jar)

 2
Author: Zephyr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-26 17:20:40

Próbowałem użyć kodu, który podał @Vinayak B. Jednak dostaję błąd mówiąc: brak dostawcy dla smtp

I created a new question for this with more information Proszę.

Mimo wszystko udało mi się to naprawić. Musiałem użyć innej poczty.jar musiałem się upewnić, że mój "Dostęp dla mniej bezpiecznych aplikacji " jest włączony.

Mam nadzieję, że to pomoże każdemu, kto ma ten sam problem. Dzięki temu ten kawałek kodu działa na google szkło też.

 2
Author: NoSixties,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:54

Cały kod podany w pozostałych odpowiedziach jest poprawny i działa dobrze, ale trochę bałagan, więc zdecydowałem się opublikować bibliotekę (wciąż w fazie rozwoju), aby łatwiej z niej korzystać: AndroidMail.

Musisz tylko utworzyć MailSender, zbudować pocztę i wysłać ją (już obsługiwane w tle za pomocą AsyncTask).

MailSender mailSender = new MailSender(email, password);

Mail.MailBuilder builder = new Mail.MailBuilder();
Mail mail = builder
    .setSender(senderMail)
    .addRecipient(new Recipient(recipient))
    .setText("Hello")
    .build();

mailSender.sendMail(mail);

Możesz otrzymać powiadomienie o wysłanej wiadomości e-mail, a także obsługuje różne typy odbiorców (TO, CC i BCC), załączniki i html:

MailSender mailSender = new MailSender(email, password);

Mail.MailBuilder builder = new Mail.MailBuilder();
Mail mail = builder
    .setSender(senderMail)
    .addRecipient(new Recipient(recipient))
    .addRecipient(new Recipient(Recipient.TYPE.CC, recipientCC))
    .setText("Hello")
    .setHtml("<h1 style=\"color:red;\">Hello</h1>")
    .addAttachment(new Attachment(filePath, fileName))
    .build();

mailSender.sendMail(mail, new MailSender.OnMailSentListener() {

    @Override
    public void onSuccess() {
        // mail sent!
    }

    @Override
    public void onError(Exception error) {
        // something bad happened :(
    }
});

Można go uzyskać przez Gradle lub Maven:

compile 'it.enricocandino:androidmail:1.0.0-SNAPSHOT'

Proszę dać mi znać, jeśli masz jakiś problem z nim! :)

 2
Author: Enrichman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-23 00:06:38

Oto wiele rozwiązań. Jednak myślę, że musimy zmienić konfigurację Gmaila, aby umożliwić dostęp z mniej bezpiecznych urządzeń. Przejdź do poniższego linku i włącz go. To działa dla mnie

Https://myaccount.google.com/lesssecureapps?pli=1

 1
Author: Nguyen Minh Hien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-02 01:53:27
 Add jar files mail.jar,activation.jar,additionnal.jar

 String sub="Thank you for your online registration" ; 
 Mail m = new Mail("emailid", "password"); 

 String[] toArr = {"[email protected]",sEmailId};
 m.setFrom("[email protected]"); 

     m.setTo(toArr);
     m.setSubject(sub);
    m.setBody(msg);



                     try{


                            if(m.send()) { 

                            } else { 

                            } 
                          } catch(Exception e) { 

                            Log.e("MailApp", "Could not send email", e); 
                          } 

  package com.example.ekktra;

   import java.util.Date;
   import java.util.Properties;

   import javax.activation.CommandMap;
   import javax.activation.DataHandler;
   import javax.activation.DataSource;
   import javax.activation.FileDataSource;
   import javax.activation.MailcapCommandMap;
   import javax.mail.BodyPart;
   import javax.mail.Multipart;
   import javax.mail.PasswordAuthentication;
   import javax.mail.Session;
   import javax.mail.Transport;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeBodyPart;
   import javax.mail.internet.MimeMessage;
   import javax.mail.internet.MimeMultipart;

   public class Mail extends javax.mail.Authenticator { 
     private String _user; 
     private String _pass; 

     private String[] _to; 

     private String _from; 

     private String _port; 
     private String _sport; 

     private String _host; 

     private String _subject; 
     private String _body; 

     private boolean _auth; 

     private boolean _debuggable; 

     private Multipart _multipart; 


   public Mail() { 
      _host = "smtp.gmail.com"; // default smtp server 
      _port = "465"; // default smtp port 
      _sport = "465"; // default socketfactory port 

      _user = ""; // username 
      _pass = ""; // password 
      _from = ""; // email sent from 
      _subject = ""; // email subject 
      _body = ""; // email body 

      _debuggable = false; // debug mode on or off - default off 
      _auth = true; // smtp authentication - default on 

      _multipart = new MimeMultipart(); 

      // There is something wrong with MailCap, javamail can not find a handler for the        multipart/mixed part, so this bit needs to be added. 
      MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
   mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
   mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
   mc.addMailcap("text/plain;; x-java-content-  handler=com.sun.mail.handlers.text_plain"); 
   mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
   mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822"); 
    CommandMap.setDefaultCommandMap(mc); 
   } 

 public Mail(String user, String pass) { 
  this(); 

  _user = user; 
   _pass = pass; 
 } 

public boolean send() throws Exception { 
   Properties props = _setProperties(); 

  if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") &&   !_subject.equals("") /*&& !_body.equals("")*/) { 
    Session session = Session.getInstance(props, this); 

    MimeMessage msg = new MimeMessage(session); 

     msg.setFrom(new InternetAddress(_from)); 

    InternetAddress[] addressTo = new InternetAddress[_to.length]; 
     for (int i = 0; i < _to.length; i++) { 
      addressTo[i] = new InternetAddress(_to[i]); 
    } 
      msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

    msg.setSubject(_subject); 
    msg.setSentDate(new Date()); 

  // setup message body 
  BodyPart messageBodyPart = new MimeBodyPart(); 
    messageBodyPart.setText(_body); 
    _multipart.addBodyPart(messageBodyPart); 

     // Put parts in message 
    msg.setContent(_multipart); 

    // send email 
    Transport.send(msg); 

    return true; 
   } else { 
     return false; 
   } 
  } 

   public void addAttachment(String filename) throws Exception { 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    DataSource source = new FileDataSource(filename); 
      messageBodyPart.setDataHandler(new DataHandler(source)); 
    messageBodyPart.setFileName(filename); 

   _multipart.addBodyPart(messageBodyPart); 
 } 

  @Override 
  public PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(_user, _pass); 
  } 

   private Properties _setProperties() { 
   Properties props = new Properties(); 

    props.put("mail.smtp.host", _host); 

  if(_debuggable) { 
    props.put("mail.debug", "true"); 
  } 

  if(_auth) { 
    props.put("mail.smtp.auth", "true"); 
   } 

    props.put("mail.smtp.port", _port); 
    props.put("mail.smtp.socketFactory.port", _sport); 
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
    props.put("mail.smtp.socketFactory.fallback", "false"); 

    return props; 
   } 

   // the getters and setters 
  public String getBody() { 
   return _body; 
 } 

 public void setBody(String _body) { 
  this._body = _body; 
 }

  public void setTo(String[] toArr) {
     // TODO Auto-generated method stub
    this._to=toArr;
 }

public void setFrom(String string) {
    // TODO Auto-generated method stub
    this._from=string;
}

 public void setSubject(String string) {
    // TODO Auto-generated method stub
    this._subject=string;
  }  


   }
 0
Author: dhiraj kakran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-25 16:15:40

Dla tych, którzy chcą używać JavaMail z Kotlinem w 2020 roku:

Po pierwsze: dodaj te zależności do swojej kompilacji.gradle file (official JavaMail Maven Dependencies)

Wdrożenie " com.słońce.mail: android-mail: 1.6.5 "

Wdrożenie " com.słońce.mail: android-aktywacja: 1.6.5 '

Implementacja " org.bouncycastle: bcmail-jdk15on:1.65 "

Implementacja " org.jetbrains.kotlinx: kotlinx-coroutines-core:1.3.7 "

Realizacja "org.jetbrains.kotlinx: kotlinx-coroutines-android:1.3.7 "

BouncyCastle jest ze względów bezpieczeństwa.

Po Drugie: dodaj te uprawnienia do AndroidManifest.xml

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

Po trzecie: podczas korzystania z SMTP, Utwórz plik konfiguracyjny

object Config {
    const val EMAIL_FROM = "[email protected]"
    const val PASS_FROM = "Your_Sender_Password"

    const val EMAIL_TO = "[email protected]"
}

Po czwarte: Utwórz swój obiekt Mailera

object Mailer {

init {
    Security.addProvider(BouncyCastleProvider())
}

private fun props(): Properties = Properties().also {
        // Smtp server
        it["mail.smtp.host"] = "smtp.gmail.com"
        // Change when necessary
        it["mail.smtp.auth"] = "true"
        it["mail.smtp.port"] = "465"
        // Easy and fast way to enable ssl in JavaMail
        it["mail.smtp.ssl.enable"] = true
    }

// Dont ever use "getDefaultInstance" like other examples do!
private fun session(emailFrom: String, emailPass: String): Session = Session.getInstance(props(), object : Authenticator() {
    override fun getPasswordAuthentication(): PasswordAuthentication {
        return PasswordAuthentication(emailFrom, emailPass)
    }
})

private fun builtMessage(firstName: String, surName: String): String {
    return """
            <b>Name:</b> $firstName  <br/>
            <b>Surname:</b> $surName <br/>
        """.trimIndent()
}

private fun builtSubject(issue: String, firstName: String, surName: String):String {
    return """
            $issue | $firstName, $surName
        """.trimIndent()
}

private fun sendMessageTo(emailFrom: String, session: Session, message: String, subject: String) {
    try {
        MimeMessage(session).let { mime ->
            mime.setFrom(InternetAddress(emailFrom))
            // Adding receiver
            mime.addRecipient(Message.RecipientType.TO, InternetAddress(Config.EMAIL_TO))
            // Adding subject
            mime.subject = subject
            // Adding message
            mime.setText(message)
            // Set Content of Message to Html if needed
            mime.setContent(message, "text/html")
            // send mail
            Transport.send(mime)
        }

    } catch (e: MessagingException) {
        Log.e("","") // Or use timber, it really doesn't matter
    }
}

fun sendMail(firstName: String, surName: String) {
        // Open a session
        val session = session(Config.EMAIL_FROM, Config.PASSWORD_FROM)

        // Create a message
        val message = builtMessage(firstName, surName)

        // Create subject
        val subject = builtSubject(firstName, surName)

        // Send Email
        CoroutineScope(Dispatchers.IO).launch { sendMessageTo(Config.EMAIL_FROM, session, message, subject) }
}

Uwaga

  • jeśli chcesz bezpieczniejszy sposób wysyłania wiadomości e-mail (i chcesz bardziej bezpieczny sposób!), użyj http, jak wspomniano w rozwiązaniach wcześniej (może dodam go później w tym odpowiedź)
  • musisz prawidłowo sprawdzić, czy telefon użytkowników ma dostęp do Internetu, w przeciwnym razie aplikacja ulegnie awarii.
  • podczas korzystania z Gmaila, włącz "mniej bezpieczne aplikacje "(to nie zadziała, gdy Gmail ma włączone dwa czynniki) https://myaccount.google.com/lesssecureapps?pli=1
  • niektóre napisy należą do: https://medium.com/@chetan.garg36/android-send-mails-not-intent-642d2a71d2ee (użył Rxjavy do swojego rozwiązania)
 0
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 14:04:01

Wysyłanie wiadomości e-mail programowo za pomocą Kotlina.

  • Proste wysyłanie e-maili, a nie wszystkie inne funkcje (jak załączniki).
  • TLS jest zawsze włączony
  • tylko 1 gradle zależność e-mail potrzebne również.

Znalazłem również tę listę usług POP poczty e-mail naprawdę pomocne:

Https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

Jak używać:

    val auth = EmailService.UserPassAuthenticator("[email protected]", "yourPassword")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("smtp.gmail.com", 465)
    
    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The kod:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private val server: String, private val port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

<uses-permission android:name="android.permission.INTERNET" />
 0
Author: Blundell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-19 07:16:12

Aby dodać załącznik, nie zapomnij dodać.

MailcapCommandMap mc = (MailcapCommandMap) CommandMap
            .getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);
 -3
Author: della pramukti raharjo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-03 14:33:48