java api发送电子邮件给另一个人--Android Studio

时间:2018-02-01 11:01:16

标签: java android email android-studio javamail

所以我想制作一个按钮发送邮件,就像申请注册一样。用户通过编辑文本向我发送他的电子邮件,并且电子邮件将从他的邮件发送到指定的电子邮件,例如“example@gmail.com”。该应用程序没有错误,但它没有发送任何电子邮件。

我已经拥有JSSEProvider,GMailsender和互联网许可。

JSSEProvider.java

import java.security.AccessController;

import java.security.Provider;



final class JSSEProvider extends Provider {



    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;

                    }

                });

    }

}

GMailsender.java

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
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 GMailSender extends javax.mail.Authenticator {

    private String user;

    private String password;

    private Session session;



    private Multipart _multipart = new MimeMultipart();

    static {

        Security.addProvider(new com.example.android.elaborasoftware.JSSEProvider());

    }



    GMailSender(String user, String password) {

        this.user = user;

        this.password = password;



        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");

        String mailhost = "smtp.gmail.com";
        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);

    }



    synchronized void sendMail(String body,

                               String sender) 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("Pedido de Registo");

            message.setDataHandler(handler);

            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setText(body);

            _multipart.addBodyPart(messageBodyPart);



            // Put parts in message

            message.setContent(_multipart);

            Transport.send(message);

        } catch (Exception ignored) {



        }

    }


    public class ByteArrayDataSource implements DataSource {

        private byte[] data;

        private String type;





        ByteArrayDataSource(byte[] data, String type) {

            super();

            this.data = data;

            this.type = type;

        }



        public ByteArrayDataSource(byte[] data) {

            super();

            this.data = data;

        }


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

        }

    }

}

我的代码如下:

Register.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class register extends AppCompatActivity{
  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    final EditText etName = findViewById(R.id.etName);
    final EditText etEmail = findViewById(R.id.etEmail);
    final EditText etNumber = findViewById(R.id.etNumber);
    final EditText etPassword = findViewById(R.id.etPassword);
    final Button btApplication = findViewById(R.id.btApplication);
    final String Email = etEmail.getText().toString();
    final String Name = etName.getText().toString();
    final String Number = etNumber.getText().toString();
    final String Password = etPassword.getText().toString();
    btApplication.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        GMailSender sender = new 
GMailSender(Email,Password);
                        sender.sendMail(Name + " send an application for 
registration by the android apk 'ElaboraSoftware' with the number: " + 
Number, Email);
                    } catch (Exception e) {

Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
                    }
                }
            }).start();
        }
    });
}

}

如果有人能提供帮助我会感激不尽。

1 个答案:

答案 0 :(得分:0)

它为我工作....发送电子邮件的最简单方法。

像这样呼叫SendMail.class

SendMail sm = new SendMail(context, "receiver@gmail.com", "Emergency Alert", email_message);
sm.execute();

<强> SendMail.class

public class SendMail extends AsyncTask<Void,Void,Void> {

//Declaring Variables
private Context context;
private Session session;

//Information to send email
private String email;
private String subject;
private String message;



//Class Constructor
public SendMail(Context context,String email,String subject,String message){
    //Initializing variables
    this.context = context;
    this.email = email;
    this.subject = subject;
    this.message = message;
}


@Override
protected Void doInBackground(Void... params) {
    //Creating properties
    Properties props = new Properties();

    //Configuring properties for gmail
    //If you are not using gmail you may need to change the values
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    //Creating a new session
    session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                //Authenticating the password
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("sender@gmail.com", "example@2018");
                }
            });

    try {
        //Creating MimeMessage object
        MimeMessage mm = new MimeMessage(session);

        //Setting sender address
        mm.setFrom(new InternetAddress(email));
        //Adding receiver
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        //Adding subject
        mm.setSubject(subject);
        //Adding messageZZ
        mm.setText(message);

        //Sending email
        Transport.send(mm);

    } catch (MessagingException e) {
        e.printStackTrace();
    }
    return null;
}

}

还在jar文件夹

中添加lib个文件

mail.jar