比较来自世界各地的卖家的域名和 IT 服务价格

如何送简单 email 软件? /有一种简单的方法吗?/

我的应用程序和按钮中有一个文本字段。 我只是想在用户的时候
按下按钮,我的应用程序应该发送 email 文本 "Hello" 在
文本字段的方向。

有一种简单的方法吗?
已邀请:

知食

赞同来自:

第一个方法

.
如果您不想与您的本机程序连接 email 或计划 gmail /通过意图/ 发送邮件,但想要 email 离开后面,请参阅下面的代码。

您可以使用此辅助类并将其调整为您的需求。


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 &amp;&amp; !"".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 &amp;&amp; !"".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 &amp;&amp; !"".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//&gt;0/ htmlBody = htmlBody.replaceAll/"#filename#",attachments.get/0/.getFilename///;
if /htmlBody.indexOf/"#header#"/&gt;=0/ htmlBody = htmlBody.replaceAll/"#header#",attachments.get/1/.getFilename///;
if /htmlBody.indexOf/"#footer#"/&gt;=0/ htmlBody = htmlBody.replaceAll/"#footer#",attachments.get/2/.getFilename///;

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

// set attachements if any
if /attachments != null &amp;&amp; attachments.size// &gt; 0/ {
for /i = 0; i &lt; 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", "&lt;" + a.getFilename// + "&gt;"/;
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;
}

}


并使用此类:


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/;
}


第二路

.
另一种选择如果您不介意使用您的本地客户端 email 或者 gmail 上 Android 发送邮件 /但是用户实际上必须在客户端中单击“发送”按钮 email/, 你能行的:


startActivity/new Intent/Intent.ACTION_SENDTO, Uri.parse/"mailto:to@gmail.com"///;


</attachment></attachment></attachment></attachment>

小姐请别说爱

赞同来自:

将此代码字符串添加到“发送”按钮


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//;
}

}
}/;


Android 自动选择设备中可用的客户,用户将自由选择任何客户端 Email, 他想要哪个

https://i.stack.imgur.com/0U50A.png
假设用户选择 gmail 作为邮政客户,它将如下所示: -

https://i.stack.imgur.com/fs92T.png
加上此方法是您不添加任何其他 jar 在一个应用程序中 &, 通过向用户提供自由来选择动作。

知食

赞同来自:

从此流中获取代码并将其导致它以便 Kotlin.

我也想做一个简单的装运 email, 不是所有其他功能 /例如,附件/.
2020 TLS 总是包括在内的,所以还有一些抓住。
只需要 1 gradle 依赖关系。

我还发现了此服务列表。 email POP 真的很有用:

https://support.office.com/en- ... 95353
如何使用:


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/
}


代码:


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"
}
}


Gradle:


dependencies {
implementation 'com.sun.mail:android-mail:1.6.4'
}


</internetaddress>

董宝中

赞同来自:

public class MainActivity extends Activity 
{
private static final String username = "emailaddress";
private static final String password = "password";
private EditText emailEdit;
private EditText subjectEdit;
private EditText messageEdit;
private Multipart _multipart;

@SuppressLint/"SdCardPath"/
@Override
protected void onCreate/Bundle savedInstanceState/ {
super.onCreate/savedInstanceState/;
setContentView/R.layout.activity_main/;

emailEdit = /EditText/ findViewById/R.id.email/;
subjectEdit = /EditText/ findViewById/R.id.subject/;
messageEdit = /EditText/ findViewById/R.id.message/;
Button sendButton = /Button/ findViewById/R.id.send/;

sendButton.setOnClickListener/new View.OnClickListener//
{
@Override
public void onClick/View view/
{
String email = emailEdit.getText//.toString//;
String subject = subjectEdit.getText//.toString//;
String message = messageEdit.getText//.toString//;

sendMail/email, 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//;
}
}

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/;
}
private Message createMessage/String email, String subject, String messageBody, Session session/ throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage/session/;
message.setFrom/new InternetAddress/"tutorials@tiemenschut.com", "Tiemen Schut"//;
message.addRecipient/Message.RecipientType.TO, new InternetAddress/email, email//;
message.setSubject/subject/;
message.setText/messageBody/;
return message;
}

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 class SendMailTask extends AsyncTask<message, void="" void,=""> {
private ProgressDialog progressDialog;

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

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

@Override
protected Void doInBackground/Message... messages/ {
try {
Transport.send/messages[0]/;
} catch /MessagingException e/ {
e.printStackTrace//;
}
return null;
}
}
}


添加三个文件 jar 在文件夹中 libs 并尽量去做
Mail.jar!

activation.jar!

additional.jar!

直接编写主题或主文本并删除 edittext, 你直接发送 email 来自您的申请。

并且不要忘记在宣言中允许访问互联网
</message,>

帅驴

赞同来自:

另一件事,我在这个网站上使用了各种答案中给出的方法,但这只是没有工作。 第一个问题是防火墙:
Transport.send/message/

发出以下例外:


javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.SocketTimeoutException: failed to connect to smtp.gmail.com/64.233.184.108 /port 465/ after 90000ms


如果发生这种情况,那么你的防火墙会阻止你。 尝试另一个网络。

我转换到另一个网络后,我收到了一封电子邮件 Google 不那么受保护的应用程序试图使用我的帐户。

解决方案是启用访问。 GMail 对于不太安全的应用程序。 这可以通过点击此处来完成:

https://support.google.com/acc ... %3Den

喜特乐

赞同来自:

改进了Matias Conradta的代码


import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

/**
* @author Ako Tulu & Mathias Conradt
*/
public class EmailService
{
public final static String CLIENT_NAME = "Android Jakarta Mail";

private String host = null;
private Integer port = null;
private boolean startTls = false;
private boolean enableSelfSigned = true;
private javax.mail.Authenticator auth = null;
private InternetAddress from = null;
private InternetAddress[] toList = null;
private InternetAddress[] ccList = null;
private InternetAddress[] bccList = null;
private Address[] replyToList = null;

private String subject = null;
private String txtBody = null;
private String htmlBody = null;
private List< Attachment > attachments = new ArrayList<>//;

private PropertyInjector injector = null;

/**
* Attachment
*/
public static class Attachment
{
protected final DataSource dataSource;

public Attachment/ final DataSource dataSource /
{
this.dataSource = dataSource;
}

/**
* BUG: InputStream has to be new instance every call.
* Stream is read to retrieve Content-Type and by SMTP write to socket,
* but stream is read once, reading twice will result in empty result.
*
* To retrive Content-Type, library has to copy the stream /be a middleman/ or
* extend itself with a peak command.
*
* public InputStream getInputStream//
*/
DataSource getDataSource//
{
return dataSource;
}
}

/**
* Authenticator
*/
public static class Authenticator extends javax.mail.Authenticator
{
private final String username;
private final String password;

public Authenticator/ final String username, final String password /
{
this.username = username;
this.password = password;
}

@Override
protected PasswordAuthentication getPasswordAuthentication//
{
return new PasswordAuthentication/ username, password /;
}
}

/**
* PropertyInjector, if custom properties are needed to be set.
*/
public interface PropertyInjector
{
void inject/ Properties properties /;
}

/**
* Callback, success if exception is null
*/
public interface Callback
{
void done/ @Nullable Exception e /;

static void handle/ @Nullable Callback c, Exception e /
{
if / c != null /
{
new Handler/ Looper.getMainLooper// /.post/ // -> {
c.done/ e /;
} /;
}
}
}

/**
* EmailService
*/
public EmailService/ final String host, final Integer port /
{
this.host = host;
this.port = port;
}

/**
* EmailService
*/
public EmailService//
{
}

/**
* Send e-mail, sync or async defined by @async var
*
* @throws MessagingException, invalid parameter
* @throws AddressException, obsecure string
*/
public void send/ boolean async, @Nullable Callback callback /
{
if / async /
{
AsyncTask.execute/ // -> {
send/ callback /;
} /;
}
else
{
send/ callback /;
}
}

/**
* Send an e-mail
*
* @throws MessagingException, invalid parameter
* @throws AddressException, obsecure string
*/
public void send/ @Nullable Callback callback /
{
try
{
Properties props = new Properties//;

Session session;

if / getAuth// != null /
{
props.put/ "mail.smtp.auth", "true" /;

session = Session.getDefaultInstance/ props, getAuth// /;
}
else
{
session = Session.getDefaultInstance/ props, null /;
}

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

msg.setFrom/ getFrom// /;
msg.setSentDate/ Calendar.getInstance//.getTime// /;
msg.setRecipients/ javax.mail.Message.RecipientType.TO, getToList// /;
msg.setRecipients/ javax.mail.Message.RecipientType.CC, getCcList// /;
msg.setRecipients/ javax.mail.Message.RecipientType.BCC, getBccList// /;
msg.setReplyTo/ getReplyToList// /;

// set header
msg.addHeader/ "X-Mailer", CLIENT_NAME /;
msg.addHeader/ "Precedence", "bulk" /;

msg.setSubject/ getSubject// /;

// set body message
Multipart mp = new MimeMultipart//;

MimeBodyPart bodyMsg = new MimeBodyPart//;
bodyMsg.setText/ getTxtBody//, "iso-8859-1" /;
bodyMsg.setContent/ getHtmlBody//, "text/html; charset=UTF-8" /;

mp.addBodyPart/ bodyMsg /;

// set attachments if any
final List< Attachment > list = getAttachments//;
if / list.size// > 0 /
{
for / int i = 0; i < list.size//; i++ /
{
Attachment a = list.get/ i /;

BodyPart att = new PreencodedMimeBodyPart/ "base64" /;

att.setFileName/ a.getDataSource//.getName// /;
att.setDataHandler/ new DataHandler/ a.getDataSource// / /;

mp.addBodyPart/ att /;
}
}
msg.setContent/ mp /;

if / getInjector// != null /
{
getInjector//.inject/ props /;
}
// set the host smtp address
props.put/ "mail.smtp.host", getHost// /;
props.put/ "mail.smtp.port", getPort// /;

props.put/ "mail.user", getFrom// /;

if / isStartTls// /
{
props.put/ "mail.smtp.starttls.enable", "true" /;
}

if / isEnableSelfSigned// /
{
props.put/ "mail.smtp.ssl.trust", getHost// /;
}

props.put/ "mail.mime.charset", "UTF-8" /;

// send it
javax.mail.Transport.send/ msg /;

Callback.handle/ callback, null /;
}
catch / Exception e /
{
Callback.handle/ callback, e /;
}
}

/**
* Parse comma separated string into @javax.mail.internet.InternetAddress list
*/
@NonNull
public static InternetAddress[] parseAddress/ final String address /
throws AddressException
{
List< InternetAddress > list = new ArrayList<>//;

if / address != null && !"".equals/ address / /
{
StringTokenizer st = new StringTokenizer/ address, "," /;

while / st.hasMoreTokens// /
{
list.add/ new InternetAddress/ st.nextToken// / /;
}
}
return list.toArray/ new InternetAddress[ list.size// ] /;
}

/**
* Resets internals for reuse
*/
public EmailService reset//
{
this.from = null;
this.toList = null;
this.ccList = null;
this.bccList = null;
this.replyToList = null;

this.subject = null;
this.txtBody = null;
this.htmlBody = null;
this.attachments = new ArrayList<>//;

return this;
}

public String getHost//
{
return host;
}

public EmailService setHost/ final String host /
{
this.host = host;

return this;
}

public Integer getPort//
{
return port;
}

public EmailService setPort/ final String port /
{
this.port = Integer.parseInt/ port /;

return this;
}

public EmailService setPort/ final int port /
{
this.port = port;

return this;
}

public boolean isEnableSelfSigned//
{
return enableSelfSigned;
}

public EmailService setEnableSelfSigned/ boolean enableSelfSigned /
{
this.enableSelfSigned = enableSelfSigned;

return this;
}

public boolean isStartTls//
{
return startTls;
}

public EmailService setStartTls/ boolean startTls /
{
this.startTls = startTls;

return this;
}

public javax.mail.Authenticator getAuth//
{
return auth;
}

public EmailService setAuth/ final javax.mail.Authenticator auth /
{
this.auth = auth;

return this;
}

public InternetAddress getFrom//
{
return from;
}

public EmailService setFrom/ final String from / throws AddressException
{
this.from = new InternetAddress/ from /;

return this;
}

public EmailService setFrom/ final InternetAddress from /
{
this.from = from;

return this;
}

public InternetAddress[] getToList//
{
return toList;
}

public EmailService setToList/ final String toList / throws AddressException
{
return setToList/ parseAddress/ toList / /;
}

public EmailService setToList/ final InternetAddress[] toList /
{
this.toList = toList;

return this;
}

public InternetAddress[] getCcList//
{
return ccList;
}

public EmailService setCcList/ final String ccList / throws AddressException
{
return setCcList/ parseAddress/ ccList / /;
}

public EmailService setCcList/ final InternetAddress[] ccList /
{
this.ccList = ccList;

return this;
}

public InternetAddress[] getBccList//
{
return bccList;
}

public EmailService setBccList/ final String bccList / throws AddressException
{
return setBccList/ parseAddress/ bccList / /;
}

public EmailService setBccList/ final InternetAddress[] bccList /
{
this.bccList = bccList;

return this;
}

public Address[] getReplyToList//
{
return replyToList;
}

public EmailService setReplyToList/ final Address[] replyTo /
{
this.replyToList = replyTo;

return this;
}

public String getSubject//
{
return subject;
}

public EmailService setSubject/ final String subject /
{
this.subject = subject;

return this;
}

public String getTxtBody//
{
return txtBody;
}

public EmailService setTxtBody/ final String txtBody /
{
this.txtBody = txtBody;

return this;
}

public String getHtmlBody//
{
return htmlBody;
}

public EmailService setHtmlBody/ final String htmlBody /
{
this.htmlBody = htmlBody;

return this;
}

public List< Attachment > getAttachments//
{
return attachments;
}

public EmailService setAttachments/ final Attachment attachment /
{
this.attachments.add/ attachment /;

return this;
}

public EmailService setAttachments/ final List< Attachment > attachments /
{
this.attachments = attachments;

return this;
}

public PropertyInjector getInjector//
{
return injector;
}

public EmailService setInjector/ final PropertyInjector injector /
{
this.injector = injector;

return this;
}

}


启用项目中的依赖项
build.gradle

Android


dependencies {
implementation 'com.sun.mail:android-mail:1.6.4'
implementation 'com.sun.mail:android-activation:1.6.4'
}


表现 EmailService


@Override
public void onCreate/ Bundle savedInstanceState /
{
super.onCreate/ savedInstanceState /;

mEmailService = new EmailService/ mConfig.getEmailHost//, mConfig.getEmailPort// /
.setEnableSelfSigned/ mConfig.getEmailSelfSignedCertEnabled// /
.setStartTls/ mConfig.getEmailSTARTTLSEnabled// /
.setAuth/ new EmailService.Authenticator/ mConfig.getEmailUsername//, mConfig.getEmailPassword// / /;
}


发送电子邮件


try
{
final ReservationNotice notice = new ReservationNotice/ mConfig.getEmailTemplateBookingReservationNotice// /
.setHeader/ mConfig.getEmailTemplateBookingReservationNoticeHeader// /
.setFooter/ mConfig.getEmailTemplateBookingReservationNoticeFooter// /;

EmailService.Attachment attachment = new EmailService.Attachment/ iCalGenerator.create/ mBooking, notice, "CalendarEvent.ics" / /;

mEmailService.reset//
.setFrom/ mBooking.getBookingEmailFromAddress// /
.setToList/ mBooking.getCustomer//.getEmail// /
.setBccList/ mBooking.getBookingEmailBCCAddress// /
.setSubject/ mBooking.getEmailTemplateBookingReservationNoticeSubject// /
.setHtmlBody/ notice.buildHTML// /
.setTxtBody/ notice.buildTXT// /
.setAttachments/ attachment /;

mEmailService.send/ true, / e / -> {
if / e != null /
{
ErrorDialog.show/ e /;
return;
}
Toast.makeText/ getContext//, R.string.email_sent, Toast.LENGTH_LONG /.show//;

} /;
}
catch / MessagingException | IOException e /
{
ErrorDialog.show/ e /;
}


预约notice是一个简单的类,用于创建电子邮件


/**
* @author Ako
*/
public abstract class BaseEmailBuilder< T extends BaseEmailBuilder >
{
protected final String mTemplate;

protected String mHeader;

protected String mFooter;

public T setHeader/ final String header /
{
mHeader = header;

return / T / this;
}

public T setFooter/ final String footer /
{
mFooter = footer;

return / T / this;
}

public BaseEmailBuilder/ final String template /
{
mTemplate = template;
}

public abstract String buildHTML//;
public abstract String buildTXT//;
public abstract String buildICal//;

}


iCalGenerator是一种包装
https://sourceforge.net/projects/ical4j/
. 目前 Android 只支持版本 2.0, 或要求 Java 1.9+.


ErrorDialog

- 此类包含构建消息的静态方法
AlertDialog.Builder

.

要回复问题请先登录注册