我试图在Android中创建一个邮件发送应用程序。

如果我使用:

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

这将启动内置的Android应用程序;我试图发送邮件按钮点击直接不使用这个应用程序。


当前回答

用于发送带有附件的邮件..

public class SendAttachment{
                    public static void main(String [] args){ 
             //to address
                    String to="abc@abc.com";//change accordingly
                    //from address
                    final String user="efg@efg.com";//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();}
                  }
                }

其他回答

你考虑过使用Apache Commons Net吗?从3.3开始,只需要一个jar(您可以使用gradle或maven依赖它),就完成了:http://blog.dahanne.net/2013/06/17/sending-a-mail-in-java-and-android-with-apache-commons-net/

如果使用“smtp.gmail.com”作为默认的smtp服务器,请注意。

谷歌将迫使您更改您的链接电子邮件帐户密码频繁由于他们过于热心的“可疑活动”政策。本质上,它将短时间内来自不同国家的重复smtp请求视为“可疑活动”。因为他们假设你(电子邮件账户持有人)一次只能在一个国家。

当谷歌系统检测到“可疑活动”时,它将阻止进一步的电子邮件,直到您更改密码。因为你已经将密码硬编码到应用程序中,每次发生这种情况,你都必须重新发布应用程序,这并不理想。这种情况发生在一周内3次对我来说,我甚至存储密码在另一个服务器上,每次谷歌强迫我更改密码时,我都动态地获取密码。

因此,我建议使用许多免费的smtp提供商之一,而不是“smtp.gmail.com”,以避免这个安全问题。使用相同的代码,但将“smtp.gmail.com”更改为新的smtp转发主机。

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

           }
}




 

GmailBackground是一个小型库,可以在后台发送电子邮件,无需用户交互:

用法:

    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主机: Smtp.gmail.com,端口:465

在清单中添加这一行:

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