【问题标题】:I cannot send an Email using the Java Mail API the email is sent but is not received or displayed in the emails sent我无法使用 Java Mail API 发送电子邮件 电子邮件已发送但未收到或未显示在已发送的电子邮件中
【发布时间】:2020-04-19 06:16:00
【问题描述】:

当我单击发送按钮时,电子邮件已发送,并且没有显示错误,但未收到电子邮件,也未出现在已发送的电子邮件中。欢迎任何帮助。

我的代码配置电子邮件类:

public class Email {

    public static void sendEmail(){
        final String username = "my_email@gmail.com";;
        final String password = "my_password";

        Properties props = new Properties();
        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");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }});
        try {

            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("my_email@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("my_receive_email@gmail.com"));
            message.setSubject("Subject");
            message.setText("Message");

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try  {
                        Transport.send(message);
                        System.out.println("Done");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

我的发送按钮代码:

btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "SEND", Toast.LENGTH_SHORT).show();
                new Email();
                Email.sendEmail();   
            }
        });

【问题讨论】:

    标签: java android email jakarta-mail


    【解决方案1】:

    这是我使用的类:

    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 JSSEProvider());
        }
    
        public GMailSender(String user, String password, String host) {
            this.user = user;
            this.password = password;
    
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            if (host != null) mailhost = host;
            props.setProperty("mail.host", mailhost);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.socketFactory.port", "587");
    
            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, String absolutePath, String fileName) 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.setContent(body, "text/plain");
               // message.setDataHandler(handler);
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(body);
                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(mbp1);
    
    
                if (absolutePath != null) {
                    MimeBodyPart mbp2 = new MimeBodyPart();
    
                    String file = absolutePath;
                    String name = "podpis";
                    if (fileName != null) name = fileName;
                    name += ".jpg";
                    DataSource source = new FileDataSource(file);
                    mbp2.setDataHandler(new DataHandler(source));
                    mbp2.setFileName(name);
                    multipart.addBodyPart(mbp2);
    
                }
                message.setContent(multipart);
    
                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){
                Log.e("GMAIL SENDER", e.getMessage());
            }
        }
    
        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");
            }
        }
    }
    

    我正在向其附加一个文件,因此您不需要两个 MimeBodyParts

    就是这样:

    String email = "email_adress_TO";
    
                if (email != null && email.length() > 2 && email.contains("@")) {
                    final GMailSender sender = new GMailSender("your_email/name", "password", "hostname");
                    try {
                        sender.sendMail("Title",
                                        "message",
                                        "email_adress_FROM",
                                        email,
                                        null,
                                        null);
                    } catch (Exception e) {
                        Log.e("SendMail", e.getMessage(), e);
                    }
    

    当然是在AsyncTask 里面。

    抱歉,我完全忘记了JSSEProvider。你去吧:

    import java.security.AccessController;
    import java.security.Provider;
    
    public class JSSEProvider extends Provider {
    
        private static final long serialVersionUID = 1L;
    
        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;
                        }
                    });
        }
    }
    

    【讨论】:

    • 谢谢,我会试试的。
    • 我删除 Security.addProvider(new JSSEProvider());现在有这个错误: GMAIL SENDER: 530 5.7.0 必须先发出 STARTTLS 命令。 x4sm17489835ljb.66 - gsmtp
    • 检查我的编辑,我已经提供了这个类。我的错。
    • 无法连接到 SMTP 主机:smtp.gmail.com,端口:587,我尝试使用端口 25 和 465 但无法正常工作
    • 你是从哪里复制这段代码的?里面有太多不必要的东西,很难说哪里出了问题。首先修复所有这些common JavaMail mistakes,然后使用新代码更新您的帖子,如果仍然无法正常工作,请发布JavaMail debug output。并确保您使用的是官方的JavaMail for Android。您不需要 JSSEProvider 或 ByteArrayDataSource。
    【解决方案2】:
    public class EmailSender {
        private JavaMailSender javaMailSender = new JavaMailSender();
    
        public void sendEmail(String to, String from, String subject, String text) {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setFrom(from);
            mailMessage.setText(text);
    
            javaMailSender.send(mailMessage);
        }
    

    【讨论】:

    • Muito obrigado irmão.
    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    相关资源
    最近更新 更多