0

I'm creating a mail sending application in Android without the intent chooser.

I tried the GmailSender Link. No errors But mail is not sending

How do i send gmail mail without user interaction?

Ganesh
  • 29
  • 1
  • This is a valid question: What's the best way to send emails programatically from Android. There have been some API deprecations recently that make it non-obvious what's the best way forward. – Cornelius Roemer Dec 27 '19 at 22:19

1 Answers1

0

Add below permission in manifest

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

Internet check

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Send a mail through below reference code

final String username = "username@gmail.com";
final String password = "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 {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from-email@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("to-email@gmail.com"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();

        messageBodyPart = new MimeBodyPart();
        String file = "path of file to be attached";
        String fileName = "attachmentName"
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
Hardik Bambhania
  • 1,732
  • 15
  • 25
  • This doesn't use any Google Sign On capability which is quite the obvious way to do it. It's much better if the user just uses Android capabilities as opposed to making your own SMTP client. I'm not convinced by this answer - there must be a better way. – Cornelius Roemer Dec 27 '19 at 22:21