Home > Software design >  Is it possible to send emails in java without using Gmail
Is it possible to send emails in java without using Gmail

Time:07-25

Background information

My Java application uses the JavaMailAPI to send emails to the users as a way of auth. I was using a Gmail account with it and I tried to log into it and it says its disabled permanently for violating Google Terms. I haven't done anything and now it doesn't work. I tried using another account and the same thing happens.

Main Question

Can I use the JavaMailAPI (or a similar Mail API) to send emails without using Gmail?

CodePudding user response:

Afaik, google API requires 2fa authentication, and if that's disabled, you'll receive an error.

But you can use any other provider with JavaMail API.

The JavaMail™ API provides classes that model a mail system. The javax.mail package defines classes that are common to all mail systems. The javax.mail.internet package defines classes that are specific to mail systems based on internet standards such as MIME, SMTP, POP3, and IMAP. The JavaMail API includes the javax.mail package and subpackages.

I hope this simple snippet will push you in the right direction.

Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
Session session = Session.getInstance(props, null);

try {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom("[email protected]");
    msg.setRecipients(Message.RecipientType.TO,
                      "[email protected]");
    msg.setSubject("JavaMail hello world example");
    msg.setSentDate(new Date());
    msg.setText("Hello, world!\n");
    Transport.send(msg, "[email protected]", "my-password");
} catch (MessagingException mex) {
    System.out.println("send failed, exception: "   mex);
}

UPD: You can try enabling 2fa in your google account and generate a password for your app using this guide. Then, replace the old password with newly generated

CodePudding user response:

You can continue to use gmail you just have to change the password you are using or switch to xoauth2.

If you want to keep using the code you have then The easiest fix for the depiction of less secure apps is to switch to using an apps password and use that in place of the password you already are using in your code.

Another option would be to swtich to using Xoauth2 javax mail appears to support that Oauth2

Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true"); // required for Gmail
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", username, oauth2_access_token);
  • Related