如何以编程方式发送简单的电子邮件?(存在一种简单的方法吗?)

Nul*_*ion 17 email android

我的应用程序上有一个文本字段,还有一个按钮.我只希望当用户按下按钮时,我的应用程序必须向文本字段上的方向发送带有"Hello"文本的电子邮件.

有一个简单的方法吗?

Mat*_*adt 36

第一种方式.如果您不希望链接到本机电子邮件程序或gmail程序(通​​过意图)发送邮件,但在后台发送电子邮件,请参阅下面的代码.

您可以使用此助手类并根据需要进行调整.

package com.myapp.android.model.service;

import android.util.Log;
import com.myapp.android.MyApp;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

public class MailService {
    // public static final String MAIL_SERVER = "localhost";

    private String toList;
    private String ccList;
    private String bccList;
    private String subject;
    final private static String SMTP_SERVER = DataService
            .getSetting(DataService.SETTING_SMTP_SERVER);
    private String from;
    private String txtBody;
    private String htmlBody;
    private String replyToList;
    private ArrayList<Attachment> attachments;
    private boolean authenticationRequired = false;

    public MailService(String from, String toList, String subject, String txtBody, String htmlBody,
            Attachment attachment) {
        this.txtBody = txtBody;
        this.htmlBody = htmlBody;
        this.subject = subject;
        this.from = from;
        this.toList = toList;
        this.ccList = null;
        this.bccList = null;
        this.replyToList = null;
        this.authenticationRequired = true;

        this.attachments = new ArrayList<Attachment>();
        if (attachment != null) {
            this.attachments.add(attachment);
        }
    }

    public MailService(String from, String toList, String subject, String txtBody, String htmlBody,
            ArrayList<Attachment> attachments) {
        this.txtBody = txtBody;
        this.htmlBody = htmlBody;
        this.subject = subject;
        this.from = from;
        this.toList = toList;
        this.ccList = null;
        this.bccList = null;
        this.replyToList = null;
        this.authenticationRequired = true;
        this.attachments = attachments == null ? new ArrayList<Attachment>()
                : attachments;
    }

    public void sendAuthenticated() throws AddressException, MessagingException {
        authenticationRequired = true;
        send();
    }

    /**
     * Send an e-mail
     * 
     * @throws MessagingException
     * @throws AddressException
     */
    public void send() throws AddressException, MessagingException {
        Properties props = new Properties();

        // set the host smtp address
        props.put("mail.smtp.host", SMTP_SERVER);
        props.put("mail.user", from);

        props.put("mail.smtp.starttls.enable", "true");  // needed for gmail
        props.put("mail.smtp.auth", "true"); // needed for gmail
        props.put("mail.smtp.port", "587");  // gmail smtp port

        /*Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("mobile@mydomain.com", "mypassword");
            }
        };*/


        Session session;

        if (authenticationRequired) {
            Authenticator auth = new SMTPAuthenticator();
            props.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(props, auth);
        } else {
            session = Session.getDefaultInstance(props, null);          
        }

        // get the default session
        session.setDebug(true);

        // create message
        Message msg = new javax.mail.internet.MimeMessage(session);

        // set from and to address
        try {
            msg.setFrom(new InternetAddress(from, from));
            msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)});
        } catch (Exception e) {
            msg.setFrom(new InternetAddress(from));
            msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
        }

        // set send date
        msg.setSentDate(Calendar.getInstance().getTime());

        // parse the recipients TO address
        java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ",");
        int numberOfRecipients = st.countTokens();

        javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients];

        int i = 0;
        while (st.hasMoreTokens()) {
            addressTo[i++] = new javax.mail.internet.InternetAddress(st
                    .nextToken());
        }
        msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo);

        // parse the replyTo addresses
        if (replyToList != null && !"".equals(replyToList)) {
            st = new java.util.StringTokenizer(replyToList, ",");
            int numberOfReplyTos = st.countTokens();
            javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos];
            i = 0;
            while (st.hasMoreTokens()) {
                addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
                        st.nextToken());
            }
            msg.setReplyTo(addressReplyTo);
        }

        // parse the recipients CC address
        if (ccList != null && !"".equals(ccList)) {
            st = new java.util.StringTokenizer(ccList, ",");
            int numberOfCCRecipients = st.countTokens();

            javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients];

            i = 0;
            while (st.hasMoreTokens()) {
                addressCC[i++] = new javax.mail.internet.InternetAddress(st
                        .nextToken());
            }

            msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC);
        }

        // parse the recipients BCC address
        if (bccList != null && !"".equals(bccList)) {
            st = new java.util.StringTokenizer(bccList, ",");
            int numberOfBCCRecipients = st.countTokens();

            javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients];

            i = 0;
            while (st.hasMoreTokens()) {
                addressBCC[i++] = new javax.mail.internet.InternetAddress(st
                        .nextToken());
            }

            msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC);
        }

        // set header
        msg.addHeader("X-Mailer", "MyAppMailer");
        msg.addHeader("Precedence", "bulk");
        // setting the subject and content type
        msg.setSubject(subject);

        Multipart mp = new MimeMultipart("related");

        // set body message
        MimeBodyPart bodyMsg = new MimeBodyPart();
        bodyMsg.setText(txtBody, "iso-8859-1");
        if (attachments.size()>0) htmlBody = htmlBody.replaceAll("#filename#",attachments.get(0).getFilename());
        if (htmlBody.indexOf("#header#")>=0) htmlBody = htmlBody.replaceAll("#header#",attachments.get(1).getFilename());
        if (htmlBody.indexOf("#footer#")>=0) htmlBody = htmlBody.replaceAll("#footer#",attachments.get(2).getFilename());

        bodyMsg.setContent(htmlBody, "text/html");
        mp.addBodyPart(bodyMsg);

        // set attachements if any
        if (attachments != null && attachments.size() > 0) {
            for (i = 0; i < attachments.size(); i++) {
                Attachment a = attachments.get(i);
                BodyPart att = new MimeBodyPart();
                att.setDataHandler(new DataHandler(a.getDataSource()));
                att.setFileName( a.getFilename() );
                att.setHeader("Content-ID", "<" + a.getFilename() + ">");
                mp.addBodyPart(att);
            }
        }
        msg.setContent(mp);

        // send it
        try {
            javax.mail.Transport.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * SimpleAuthenticator is used to do simple authentication when the SMTP
     * server requires it.
     */
    private static class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            String username = DataService
                    .getSetting(DataService.SETTING_SMTP_USER);
            String password = DataService
                    .getSetting(DataService.SETTING_SMTP_PASSWORD);

            return new PasswordAuthentication(username, password);
        }
    }

    public String getToList() {
        return toList;
    }

    public void setToList(String toList) {
        this.toList = toList;
    }

    public String getCcList() {
        return ccList;
    }

    public void setCcList(String ccList) {
        this.ccList = ccList;
    }

    public String getBccList() {
        return bccList;
    }

    public void setBccList(String bccList) {
        this.bccList = bccList;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setTxtBody(String body) {
        this.txtBody = body;
    }

    public void setHtmlBody(String body) {
        this.htmlBody = body;
    }

    public String getReplyToList() {
        return replyToList;
    }

    public void setReplyToList(String replyToList) {
        this.replyToList = replyToList;
    }

    public boolean isAuthenticationRequired() {
        return authenticationRequired;
    }

    public void setAuthenticationRequired(boolean authenticationRequired) {
        this.authenticationRequired = authenticationRequired;
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用这个类:

MailService mailer = new MailService("from@mydomain.com","to@domain.com","Subject","TextBody", "<b>HtmlBody</b>", (Attachment) null);
try {
    mailer.sendAuthenticated();
} catch (Exception e) {
    Log.e(AskTingTing.APP, "Failed sending email.", e);
}
Run Code Online (Sandbox Code Playgroud)

第二种方式.另一种选择,如果您不介意在Android上使用本机电子邮件客户端或gmail发送邮件(但用户实际上必须最终在电子邮件客户端中点击发送按钮),您可以这样做:

startActivity(new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:to@gmail.com")));
Run Code Online (Sandbox Code Playgroud)

  • 您需要将javax邮件的activation.jar/mail.jar添加到您的lib文件夹(如果它尚不存在,则在项目根文件夹中创建它).您可以从网上下载jar,即http://www.oracle.com/technetwork/java/index-138643.html (2认同)

Hit*_*ahu 12

在提交按钮中添加此行代码

 final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                              emailIntent.setType("text/plain");
                              emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String\[\]{  "serveroverloadofficial@gmail.com"});
                              emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello There");
                              emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Add Message here");


                                emailIntent.setType("message/rfc822");

                            try {
                                startActivity(Intent.createChooser(emailIntent,
                                        "Send email using..."));
                            } catch (android.content.ActivityNotFoundException ex) {
                                Toast.makeText(getActivity(),
                                        "No email clients installed.",
                                        Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
Run Code Online (Sandbox Code Playgroud)

Android将自动选择您的设备中可用的客户端,用户可以自由选择他想要的任何电子邮件客户端

意图app选择器

假设用户选择gmail作为邮件客户端,它将如下所示: -

简单发送邮件

此方法的另一点是,您没有在App中添加任何额外的jar并且允许用户自由选择操作.


Blu*_*ell 5

从这个线程中取出代码并将其整理到 Kotlin 中。

我也只想做简单的电子邮件发送,而不是所有其他功能(如附件)。2020 TLS 始终开启,因此也进行了一些整理。还只需要 1 个 gradle 依赖项。

我还发现此电子邮件 POP 服务列表非常有用:

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

如何使用:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("to@email.com"))
    val from = InternetAddress("from@email.com")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch {
        emailService.send(email)
    }
Run Code Online (Sandbox Code Playgroud)

编码:

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 var server: String, private var 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"
    }
}
Run Code Online (Sandbox Code Playgroud)

摇篮:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
}
Run Code Online (Sandbox Code Playgroud)