如果我使用:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
这将启动内置的Android应用程序;我正在尝试在按钮点击时直接发送邮件,而不使用该应用程序。
这会启动内置的 Android 应用程序;我想在按钮单击时直接发送电子邮件,而无需使用该应用程序。
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
这将启动内置的Android应用程序;我正在尝试在按钮点击时直接发送邮件,而不使用该应用程序。
这会启动内置的 Android 应用程序;我想在按钮单击时直接发送电子邮件,而无需使用该应用程序。
使用JavaMail API和Gmail身份验证在Android中发送电子邮件。
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("username@gmail.com", "password");
sender.sendMail("This is Subject",
"This is Body",
"user@gmail.com",
"user@yahoo.com");
} 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;
}
});
}
}
如果您不知道如何操作,请查看this的帖子。
并且不要忘记在您的清单中添加以下行:
<uses-permission android:name="android.permission.INTERNET" />
通过访问此链接,调整您的帐户访问设置以使用不太安全的应用程序:
https://www.google.com/settings/security/lesssecureapps。
更新 2023: 不再支持使用较不安全的应用程序。要访问您的帐户,您需要启用双因素身份验证,并使用下面图片中提供的设置使用应用程序密码:
运行项目并检查您的收件人邮件帐户以查看邮件。
P.S.:请记住,在Android中直接从Activity执行网络操作是不允许的。因此,强烈建议使用AsyncTask
或IntentService
以避免遇到主线程上的网络异常。
感谢您提供宝贵的信息。代码正常运行。通过添加以下代码,我也能够添加附件。
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);
filename
变量,您必须指定文件路径。例如:String path = Environment.getExternalStorageDirectory().getPath() + "/temp_share.jpg";
- user6649667无法连接到SMTP主机: smtp.gmail.com,端口:465
在您的清单文件中添加此行:
<uses-permission android:name="android.permission.INTERNET" />
eu.ocathain.com.sun.mail:javax.mail:1.5.2
。 - artbristol为了帮助那些在SDK Target > 9中遇到网络主线程异常的人。这是使用droopie上面的代码,但对于任何其他类似情况也适用。
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
android.os.NetworkOnMainThreadException
您可以按以下方式使用AsyncTask
public void onClickMail(View view) {
new SendEmailAsyncTask().execute();
}
class SendEmailAsyncTask extends AsyncTask <Void, Void, Boolean> {
Mail m = new Mail("from@gmail.com", "my password");
public SendEmailAsyncTask() {
if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(), "SendEmailAsyncTask()");
String[] toArr = { "to mail@gmail.com"};
m.setTo(toArr);
m.setFrom("from mail@gmail.com");
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;
}
}
使用SMTP是一种方法,其他人已经指出了如何执行此操作的方式。请注意,在执行此操作时,您完全绕过了内置邮件应用程序,并且必须提供SMTP服务器的地址、该服务器的用户名和密码,无论是在代码中静态地提供还是从用户查询获取。
另一种方法涉及一个简单的服务器端脚本,例如php,它需要一些URL参数并使用它们发送邮件。这种方式,您只需从设备进行HTTP请求(可以轻松地通过内置库完成),而不需要在设备上存储SMTP登录数据。与直接使用SMTP相比,这是更多的间接性,但由于使用PHP轻松地进行HTTP请求并发送邮件,甚至可能比直接使用SMTP更简单。
如果要从用户已经在手机上注册的默认邮件帐户发送邮件,则必须采取其他方法。如果您有足够的时间和经验,您可能希望检查Android电子邮件应用程序的源代码,以查看是否提供了某个入口点以在没有用户交互的情况下发送电子邮件(我不知道,但也许会有一个)。也许您甚至可以找到一种方法来查询用户帐户详细信息(因此您可以将其用于SMTP),尽管我极度怀疑这是可能的,因为这将是一个巨大的安全风险,而Android构建得相当安全。
这里有一个备选版本,对我也起作用,并且有附件(已经在上面发布过了,但是完整版本,不像源链接,人们说它缺少数据,无法正常工作)。
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 …..
}
并在活动中调用它...
@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("gmailusername@gmail.com", "password");
String[] toArr = {"bla@bla.com", "lala@lala.com"};
m.setTo(toArr);
m.setFrom("wooo@wooo.com");
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);
}
}
});
}
Could not send email android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
问题,需要查看此解决方案:https://dev59.com/Deo6XIcBkEYKwwoYIAsf - jgrochaGmailBackground是一个小型库,可在没有用户交互的情况下后台发送电子邮件:
用法:
BackgroundMail.newBuilder(this)
.withUsername("username@gmail.com")
.withPassword("password12345")
.withMailto("toemail@gmail.com")
.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();
配置:
repositories {
// ...
maven { url "https://jitpack.io" }
}
dependencies {
compile 'com.github.yesidlazaro:GmailBackground:1.2.0'
}
权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
另外,对于附件,您需要设置 READ_EXTERNAL_STORAGE 权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
(我已经亲自测试过)
如果将“smtp.gmail.com”作为默认的SMTP服务器,需注意以下警告:
由于Google过于热衷于其“可疑活动”政策,他们会强制你频繁更改链接电子邮件帐户密码。实际上,如果在短时间内来自不同国家的重复SMTP请求被视为“可疑活动”,它会将其视为威胁行为。因为他们认为你(电子邮件帐户持有者)一次只能在一个国家。
当Google系统发现“可疑活动”时,它将阻止进一步的电子邮件发送,直到你更改密码。因为你已经将密码硬编码到应用程序中,所以每次发生这种情况,你都需要重新发布该应用程序,这并不理想。我一周内就遇到了三次这样的情况,我甚至将密码存储在另一台服务器上,并动态获取每次Google强制我更改密码。
因此,我建议使用许多免费的SMTP提供商之一而不是“smtp.gmail.com”以避免这种安全问题。使用相同的代码,但将“smtp.gmail.com”更改为新的SMTP转发主机即可。
编辑:JavaMail 1.5.5 声称支持Android,所以您不需要其他任何东西。
我已经将最新的JavaMail(1.5.4)移植到了Android上。它可以在Maven Central中获得,只需将以下内容添加到build.gradle
中即可~~
compile 'eu.ocathain.com.sun.mail:javax.mail:1.5.4'
您可以按照官方的教程进行操作。
源代码可在此处获取:https://bitbucket.org/artbristol/javamail-forked-android