I'm working on an application that uses the JavaMail API to send an email, but I keep getting errors. I'm using Eclipse to code it and I'm using gmail to send it. I took out my real password for obvious reasons so you're probably going to need to replace that with your own if you need to experiment. Now that I've fixed some stuff thanks to you guys, I think I'm getting a timeout error because it takes a long time until it displays the error, but beyond that much, I haven't the foggiest clue. Thanks in advance for any help or advice once more.
Code:
package com.brighamcampbell.sunrisegundersonmail;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class Mail {
public static void main(String[] args) throws MessagingException,
UnsupportedEncodingException {
Properties mailProps = new Properties();
mailProps.put("mail.smtp.from", "butterscotchdreamer23#gmail.com");
mailProps.put("mail.smtp.host", "smtp.gmail.com");
mailProps.put("mail.smtp.ssl.trust", "smtp.gmail.com");
mailProps.put("mail.smtp.port", "465");
mailProps.put("mail.smtp.auth", true);
mailProps.put("mail.smtp.starttls.enable", "true");
Session mailSession = Session.getDefaultInstance(mailProps, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("butterscotchdreamer23#gmail.com", "password");
}
});
MimeMessage message = new MimeMessage(mailSession);
//set the email sender
message.setFrom(new InternetAddress("butterscotchdreamer23#gmail.com"));
//set the email recipients
String[] emails = { "butterscotchdreamer23#gmail.com" };
InternetAddress dests[] = new InternetAddress[emails.length];
for (int i = 0; i < emails.length; i++) {
dests[i] = new InternetAddress(emails[i].trim().toLowerCase());
}
message.setRecipients(Message.RecipientType.TO, dests);
//set the email subject
message.setSubject("test");
//set the email content
message.setText("this is a test");
//send
System.out.println("sending...");
Transport.send(message);
System.out.println("done sending email!");
}
}
Error:
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2041)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at com.brighamcampbell.sunrisegundersonmail.Mail.main(Mail.java:56)
Thanks for the patience!
Clearly the mail server doesn't support STARTTLS, so you shouldn't enable it.
Try removing the 3 sslfactory properties as it is not needed anymore for javamail.You should be able to connect that way.
Note:The gmail server definitely support STARTTLS:
x#test:~/$ telnet smtp.gmail.com 587
Trying 74.125.136.108...
Connected to gmail-smtp-msa.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP vv9sm12826892wjc.35 - gsmtp
EHLO me
250-mx.google.com at your service, [147.58.51.121]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
QUIT
General Gmail instructions are here, general connection debugging tips are here, and a list of common mistakes is here. Possibly you're running into a firewall or anti-virus program that's intercepting your attempt to connect. If you still can't make it work, post the JavaMail debug output.
Related
So since the 31 of may google has disabled the option for "Less secure apps", so I have been using the Java mail API, and since the update i can no longer send emails using the Gmail smtp.
This is the error I'm getting:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials n13-20020a5d400d000000b0020ff7246934sm4970874wrp.95 - gsmtp
I switched to an outlook mail and it seems to work fine, but i was wondering if there is a way to use a Gmail account
Less secure apps & your Google Account
You could try authentification via "App password".
On your Google account:
set 2-Step Verification ON
create 16-character "App password"(
How to create app password) -> result should be similar to:
16-character "App password"
Instead of Google account password use 16-character password
MailMessage mail = new MailMessage();
foreach (string receiver in DolociPrejemnike())
mail.To.Add(receiver);
mail.From = new MailAddress("app_gmail#gmail.com", "No replay"); //poĊĦiljatelj (vedno enak)
mail.Subject = SetSubject();
mail.Body = SetBody();
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("app_gmail#gmail.com", "xtqapucsmyvqmvxp"); // Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
So thanks for all the replays! i have fixed this issue by doing this:
I have enabled the "App password for windows machines"
Then i simply changed the password from the email password to the google generated one
and changed the code to the following:
public class JavaMailUtil {
public static void sendMail(String recepient,String order) throws Exception {
Properties properties=new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
String myAccountEmail="yourEmailAddress#gmail.com";
String password="Generated Windows machine password from google";
Session session=Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccountEmail, password);
}
});
Message message=prepareMessage(session,myAccountEmail,recepient,order);
Transport.send(message);
System.out.println("Message Sent successfully");
}
private static Message prepareMessage(Session session,String from,String to,String orderInfo) {
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));a
message.setSubject("Your subject here");
message.setText(");
return message;
} catch (AddressException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Now that you can no longer use login and password with Googles smtp server the only option really is to use XOauth2
I havent used Jakarta before but it appears to support it. You should look into OAuth2 Support
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);
Apps password
option two is to go to your google account and generate an apps password
When running your code use the password generated instead of the actual users password. The main issue with this being there is no telling how long google will continue to support apps password.
To those who followed the other answers but are still getting the "Authentication Failed" error when using an app password, a key point is that this solution is NOT working for XOAUTH2 if you are using that or are following a guide saying to use oauth2.
So in the following code:
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Simply change it to the following:
props.put("mail.imap.auth.mechanisms", "XOAUTH");
and it should work, keeping all else the same.
Note: please enable 2-factor authentication in google account before proceeding.
Less secure apps (https://myaccount.google.com/u/0/lesssecureapps) options is no longer available.
Instead use another way of using apppasswords provided by google.
https://myaccount.google.com/u/0/apppasswords
Use 16 digit code provided by google instead of password and that will serve as authentication token.
So since the 31 of may google has disabled the option for "Less secure apps", so I have been using the Java mail API, and since the update i can no longer send emails using the Gmail smtp.
This is the error I'm getting:
javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials n13-20020a5d400d000000b0020ff7246934sm4970874wrp.95 - gsmtp
I switched to an outlook mail and it seems to work fine, but i was wondering if there is a way to use a Gmail account
Less secure apps & your Google Account
You could try authentification via "App password".
On your Google account:
set 2-Step Verification ON
create 16-character "App password"(
How to create app password) -> result should be similar to:
16-character "App password"
Instead of Google account password use 16-character password
MailMessage mail = new MailMessage();
foreach (string receiver in DolociPrejemnike())
mail.To.Add(receiver);
mail.From = new MailAddress("app_gmail#gmail.com", "No replay"); //poĊĦiljatelj (vedno enak)
mail.Subject = SetSubject();
mail.Body = SetBody();
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("app_gmail#gmail.com", "xtqapucsmyvqmvxp"); // Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
So thanks for all the replays! i have fixed this issue by doing this:
I have enabled the "App password for windows machines"
Then i simply changed the password from the email password to the google generated one
and changed the code to the following:
public class JavaMailUtil {
public static void sendMail(String recepient,String order) throws Exception {
Properties properties=new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
String myAccountEmail="yourEmailAddress#gmail.com";
String password="Generated Windows machine password from google";
Session session=Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(myAccountEmail, password);
}
});
Message message=prepareMessage(session,myAccountEmail,recepient,order);
Transport.send(message);
System.out.println("Message Sent successfully");
}
private static Message prepareMessage(Session session,String from,String to,String orderInfo) {
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));a
message.setSubject("Your subject here");
message.setText(");
return message;
} catch (AddressException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Now that you can no longer use login and password with Googles smtp server the only option really is to use XOauth2
I havent used Jakarta before but it appears to support it. You should look into OAuth2 Support
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);
Apps password
option two is to go to your google account and generate an apps password
When running your code use the password generated instead of the actual users password. The main issue with this being there is no telling how long google will continue to support apps password.
To those who followed the other answers but are still getting the "Authentication Failed" error when using an app password, a key point is that this solution is NOT working for XOAUTH2 if you are using that or are following a guide saying to use oauth2.
So in the following code:
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Simply change it to the following:
props.put("mail.imap.auth.mechanisms", "XOAUTH");
and it should work, keeping all else the same.
Note: please enable 2-factor authentication in google account before proceeding.
Less secure apps (https://myaccount.google.com/u/0/lesssecureapps) options is no longer available.
Instead use another way of using apppasswords provided by google.
https://myaccount.google.com/u/0/apppasswords
Use 16 digit code provided by google instead of password and that will serve as authentication token.
I've tried a bunch of alterations to my code but with no effect. The code itself does not return any errors but instead gives a success message. I am using gmail as my relay.
P.S, I commented out $mail->IsSMTP(); because I saw a similar question here that used it as a fix, I was getting an "smtp failed to connect" error.
I am using PHPmailer 6.0.
Here is my code:
<?php
require_once('vendor/autoload.php');
define('GUSER', 'example#gmail.com'); // GMail username
define('GPWD', '*********'); // GMail password
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer\PHPMailer\PHPMailer(true); // create a new object
//$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 4; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail message', 'Hello World!');
if (smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail message', 'Hello World!')) {
// do something
}
if (!empty($error)) echo $error;
?>
If I uncomment $mail->IsSMTP(); I get this error log:
2017-12-27 07:58:54 Connection: opening to smtp.gmail.com:465, timeout=300, options=array()
2017-12-27 07:58:54 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:465 (Network is unreachable) [/srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/SMTP.php line 325]
2017-12-27 07:58:54 SMTP ERROR: Failed to connect to server: Network is unreachable (101)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Fatal error: Uncaught PHPMailer\PHPMailer\Exception: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting in /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php:1726 Stack trace: #0 /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Wed, 27 D...', 'Hello World!\r\n') #1 /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->postSend() #2 /srv/disk2/2564570/www/consorttest.dx.am/mailtest.php(23): PHPMailer\PHPMailer\PHPMailer->send() #3 /srv/disk2/2564570/www/consorttest.dx.am/mailtest.php(32): smtpmailer('to#mail.com', 'from#mail.com', 'yourName', 'test mail messa...', 'Hello World!') #4 {main} thrown in /srv/disk2/2564570/www/consorttest.dx.am/vendor/phpmailer/phpmailer/src/PHPMailer.php on line 1726
You're not "using gmail as your relay" if you comment out isSMTP() because then it's not using SMTP at all, and will ignore all your SMTP settings. You're sending via your local mail server using PHP's built-in mail function.
When sending through gmail, you can't use arbitrary from addresses, though you can preset aliases in your gmail account.
You've based your code on a very old and obsolete example - use the gmail one provided with PHPMailer.
The most important part of the error output is: Network is unreachable - that probably means your ISP blocks outbound SMTP - are you by any chance using GoDaddy?
Next up, you have a basic misconfiguration: you're connecting to port 465 using SMTPSecure = 'tls', which means it will try to use SMTP+STARTTLS explicit TLS encryption, and that just won't work on port 465. This is a key reason to use the provided examples - they don't make basic errors like this.
Every one of these things is covered in the troubleshooting guide the error links to.
I'm having a trouble sending an email using Google's SMTP Server. I've looked for a solution but i have not found one. So here's the code.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
...
...
...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
Properties props = new Properties();
props.put("true", "mail.smtp.auth");
props.put("true","mail.smtp.starttls.enable");
props.put("smtp.gmail.com", "mail.smtp.host");
props.put("587", "mail.smtp.port");
Session sess=Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("myemail#gmail.com", "mypassword");
}
}
);
try{
Message message= new MimeMessage(sess);
message.setFrom(new InternetAddress("myemail#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("myemail#gmail.com"));
message.setSubject("message");
message.setText("text");
Transport.send(message);
JOptionPane.showMessageDialog(null, "Sent!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
Each time when i press the button, it show me this error:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
I've tried 3 ports: 25, 465, 587 , but it always gives me that error. I even made new rules for the port 25 to the firewall settings, but that doesn't seem to do the trick. Any thoughts what am i doing wrong? Could hibernate cause the problem? Because i'm using it in this project. Plus, i have installed mysql.
Your program is trying to connect to a local port, that's why it failed. If your listing is real code, you got the key and value backwards in the props.set statements.
I am trying to send mail using SmtpClient and below is my code.
SmtpClient client_ = new SmtpClient("relay-hosting.secureserver.net", 25);
//client_.DeliveryMethod = SmtpDeliveryMethod.Network;
//client_.EnableSsl = true;
// client_.UseDefaultCredentials = false;
//client_.Credentials = new System.Net.NetworkCredential(_fromAddress, _password);
MailAddress from_ = new MailAddress(_fromAddress, _fromName);
MailMessage msg_ = new MailMessage(from_, from_);
msg_.Subject = "Subject";
StringBuilder body_ = new StringBuilder();
body_.AppendLine("Line1");
body_.AppendLine("===============================================================================================");
body_.AppendLine("Line2");
body_.AppendLine("===============================================================================================");
body_.AppendLine("line2");
body_.AppendLine("===============================================================================================");
msg_.Body = body_.ToString();
msg_.IsBodyHtml = true;
client_.Send(msg_);
I am getting TimeOut error. When Same smtp configuration using in email client on my machine, it send the mail immediately. I don't know what can be cause. Also when I used my Gmail account with gmail smpt server it worked.
Most consumer ISPs block port 25 to prevent you from running a mail server.
Therefore, you cannot connect to port 25 from your house.
You can ask them for an alternate port.
Try port 587; it's commonly used as well.