我试图在Android中创建一个邮件发送应用程序。
如果我使用:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
这将启动内置的Android应用程序;我试图发送邮件按钮点击直接不使用这个应用程序。
我试图在Android中创建一个邮件发送应用程序。
如果我使用:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
这将启动内置的Android应用程序;我试图发送邮件按钮点击直接不使用这个应用程序。
当前回答
那些正在获得ClassDefNotFoundError的人尝试移动这三个jar文件到你的项目的lib文件夹,它为我工作!!
其他回答
在Android中使用JavaMail API使用Gmail身份验证发送电子邮件。
创建示例项目的步骤:
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;
}
});
}
}
将下面链接中的3个罐子添加到你的Android项目中
mail.jar activation.jar additional.jar
点击这里-如何添加外部罐子
别忘了在你的清单上加上这一行:
<uses-permission android:name="android.permission.INTERNET" />
只需点击下面的链接,更改帐户访问不太安全的应用程序 https://www.google.com/settings/security/lesssecureapps
运行项目并检查收件人邮件帐户。
另外,别忘了你不能在android的任何活动中进行网络操作。 因此,建议使用AsyncTask或IntentService来避免主线程网络异常。
Jar文件:https://code.google.com/archive/p/javamail-android/
无法连接到SMTP主机: Smtp.gmail.com,端口:465
在清单中添加这一行:
<uses-permission android:name="android.permission.INTERNET" />
package io.formics.tourguide
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Credentials
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_feedback.*
import org.jetbrains.annotations.Async
import java.lang.Exception
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource
import javax.mail.*
import javax.mail.internet.*
class FeedbackActivity : AppCompatActivity() {
val props = Properties()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feedback)
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");
btnSendEmail.setOnClickListener {
Thread {
try {
sendEmail()
// Your implementation
} catch (ex: Exception) {
ex.printStackTrace()
}
}.start()
}
}
private fun sendEmail() {
try {
val session = Session.getInstance(props,
object : javax.mail.Authenticator() {
//Authenticating the password
override fun getPasswordAuthentication(): javax.mail.PasswordAuthentication {
return PasswordAuthentication("abc@xyz.com", "password")
}
})
val message = MimeMessage(session);
message.setFrom(InternetAddress("abc@xyz.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(editCC.text.toString())
)
message.subject = editSubject.text.toString()
message.setText(
"Dear Mail Crawler,"
+ "\n\n No spam to my email, please!"
);
//val messageBodyPart = MimeBodyPart();
//val multipart = MimeMultipart();
//val file = "path of file to be attached";
// val fileName = "attachmentName"
// val source = FileDataSource(file);
//messageBodyPart.setDataHandler(DataHandler(source));
//messageBodyPart.setFileName(fileName);
//multipart.addBodyPart(messageBodyPart);
//message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (e: MessagingException) {
throw RuntimeException(e);
}
}
}
其他答案中提供的所有代码都是正确的,运行正常,但有点混乱,所以我决定发布一个库(尽管仍在开发中),以更简单的方式使用它:AndroidMail。
你只需要创建一个MailSender,构建一个邮件并发送它(已经在后台处理了一个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);
您可以收到通知的电子邮件发送,它还支持不同的收件人类型(TO,抄送和密件抄送),附件和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 :(
}
});
您可以通过Gradle或Maven获取:
compile 'it.enricocandino:androidmail:1.0.0-SNAPSHOT'
如果你有任何问题,请告诉我!:)
我试着用@Vinayak B提交的代码。然而,我得到一个错误说:没有提供smtp
我在这里创建了一个新问题,提供了更多信息
我终于自己修好了。我得用另一个邮件罐 我必须确保我的“不太安全的应用程序访问权限”被打开。
我希望这能帮助那些有同样问题的人。这样做后,这段代码也可以在谷歌玻璃上工作。