Javamail: second time connection failure: connect to different host and port - smtp

I am sending mails in a Java EE project using Javamail and I am testing in localhost. I can send the mail the first time I use the code below, but the second time I cannot, and the console shows it tries to connect to localhost, which doesn't happen the first time.
1st time console messages:
DEBUG: JavaMail version 1.5.1
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: need username and password for authentication
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.1and1.es", port 465, isSSL false
220 kundenserver.de (mreue104) Nemesis ESMTP Service ready
DEBUG SMTP: connected to host "smtp.1and1.es", port: 465
....(more host/connection/email content details, but the connection is established)
2nd time console message:
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "localhost", port 25, isSSL false
And it stops and does nothing.
properties (smtp segment):
mail.smtp.protocol=smtp
mail.smtp.useTSL=true
mail.smtp.auth=true
#mail.smtp.host=smtp.redfinanciera.es
mail.smtp.host=smtp.1and1.es
mail.smtp.port=465
mail sender code:
public CCorreo mandarCorreo(CCorreoForm form) {
InputStream input = null;
Properties prop = null;
CCorreo correo = null;
try {
//leer prop y mandar mensajes
input = MailSmtpSender.class.getResourceAsStream("/config/properties/mail.properties");
prop = new Properties();
prop.load(input);
final String smtpUser = prop.getProperty("mail.smtp.user");
final String smtpPassword = prop.getProperty("mail.smtp.pass");
//prop setting de smtp.
prop.setProperty("mail.smtp.connectiontimeout", "5000");
prop.setProperty("mail.smtp.timeout", "5000");
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.debug", "true");
//socket factory port: default if null
prop.put("mail.smtp.socketFactory.port", "465");
// prop.put("mail.smtp.socketFactory.port", "*");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.put("mail.smtp.socketFactory.fallback", "false");
//crear una sesion. con autentificacion SSL
Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUser, smtpPassword);
}
});
//construir message
MimeMessage message = new MimeMessage(session);
message.setFrom(prop.getProperty("mail.smtp.from"));
if (!StringUtils.isEmpty(form.getCuerpo())){
message.setText(form.getCuerpo(), "UTF8");
} else {
message.setText("");
}
message.setSubject(form.getAsunto(), "UTF8");
//construir receptor. sacar de form.
String[] addressesString = {form.getReceptor()};
InternetAddress addresses[] = new InternetAddress[addressesString.length];
for (int i = 0; i < addressesString.length; i++){
addresses[i] = new InternetAddress(addressesString[i].trim().toLowerCase());
}
message.setRecipients(Message.RecipientType.TO, addresses);
//formar el correo, rellenar todas las partes de el.
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(form.getCuerpo(), "text/html;charset=utf-8");
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new Date());
//establecer un Transport y mandar el mensaje
Transport.send(message);
} catch (Exception e) {
throw new RuntimeException("Se ha producido un error al mandar el correo. Mensaje: " + e.getMessage());
} finally {
prop.clear();
try {
input.close();
} catch (IOException e) {
System.out.println("Se ha producido un error al mandar el correo. Mensaje: " + e.getMessage());
}
}
return correo;
}
So here's the question: why does it connect to smtp server using port 465 the first time, but in second try it connects to localhost and using port 25??? It's totally weird.
Edit:
I open a lightbox/modal in AngularJS to send a email. Once the email is sent the lightbox is closed and the main page is shown again. I found that if I don't refresh the main page, I cannot send an email again, but if I do a refresh, it works fine. I am trying to figure out why it is, and hoping to find answers about this, too.

Your code contains many of the common JavaMail mistakes described in the JavaMail FAQ.
In particular, your problem is most likely caused by your use of Session.getDefaultInstance instead of Session.getInstance, but you'll want to fix all the problems in the above link.

Related

PHPMailer Connects but not sending (Google XOAUTH2)

Can anyone interpret the following output from PHPMailer and diagnose the problem? I have successfully tested my code in isolation but after incorporating into an application it fails
2021-08-19 14:25:31 3 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array()
2021-08-19 14:25:31 3 Connection: opened
2021-08-19 14:25:31 2 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP q184sm1663611qkd.35 - gsmtp
2021-08-19 14:25:31 1 CLIENT -> SERVER: EHLO localhost
2021-08-19 14:25:31 2 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [2607:fea8:e2c0:5dd:6c0a:3ddc:897:57d9]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
2021-08-19 14:25:31
2021-08-19 14:25:31 1 CLIENT -> SERVER: QUIT
2021-08-19 14:25:32 2 SERVER -> CLIENT: 221 2.0.0 closing connection q184sm1663611qkd.35 - gsmtp
2021-08-19 14:25:32 3 Connection: closed
The code is based on the XOAUTH2 example in the PHPMailer documentation. The essential function is here:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
class MainController extends Controller
{
function sendPHPMail($to, $name, $reply, $subject, $body, $attach, $type) {
// This function sends an HTML email via Google's SMTP server using XOAUTH2
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_CONNECTION;
$mail->Debugoutput = function($str, $level) {
file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\t$level\t$str\n", FILE_APPEND | LOCK_EX);
};
//Set the hostname of the mail server
$mail->Host = $this->f3->get('mailHost');
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$emailUser = $this->f3->get('mailUser');
$clientId = $this->f3->get('oauthClientID');
$clientSecret = $this->f3->get('oauthClientSecret');
// Refresh Token obtained by configuring and running get_oauth_token.php
// after setting up an app in Google Developer Console.
$refreshToken = $this->f3->get('oauthRefreshToken');
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $emailUser,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($emailUser, "Mississippi Valley Textile Museum");
$mail->addReplyTo($reply);
//Set who the message is to be sent to
$mail->addAddress($to, $name);
//Set the subject line
$mail->Subject = $subject;
//Set HTML message body, convert referenced images to embedded
//Specify a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This email is HTML; enable HTML mail if you cannot see it.';
//Add attachment if specified
if ($attach) {
$mail->addStringAttachment($attach, "MVTM{$type}.pdf"); }
//send the message, catch and log errors
try {
return $mail->send();
} catch (phpmailerException $e) {
file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\n$e->errorMessage\n", FILE_APPEND | LOCK_EX);
//Pretty error messages from PHPMailer
return false;
} catch (Exception $e) {
file_put_contents('smtp.txt', gmdate('Y-m-d H:i:s'). "\n$e->errorMessage\n", FILE_APPEND | LOCK_EX);
// error messages from anything else
return false;
}
}
It appears to get by the initial connection but not the actual transmission to the smtp server
Solved. OK, there is nothing wrong with my code as shown here. The problem was in my app config file which hold the ClientSecret and RefreshToken. I had used single rather than double quotes which caused an escape to be misinterpretted. 3 days wasted but lesson learned.

SMTP error when using $_ENV for credentials in PHPMailer

When using hard-coded username / email / password I have no problem getting a message sent with phpmailer. But when I use $_ENV to hide the credentials I get the smtp error as shown here:
2020-09-08 15:50:51 SERVER -> CLIENT: 220 dd45234.kasserver.com ESMTP
2020-09-08 15:50:51 CLIENT -> SERVER: EHLO browsegenres-f3.loc
2020-09-08 15:50:51 SERVER -> CLIENT: 250-dd45234.kasserver.com250-PIPELINING250-SIZE 102400000250-VRFY250-ETRN250-STARTTLS250-AUTH PLAIN LOGIN250-AUTH=PLAIN LOGIN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2020-09-08 15:50:51 CLIENT -> SERVER: STARTTLS
2020-09-08 15:50:51 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2020-09-08 15:50:51 CLIENT -> SERVER: EHLO xxxxxxxxxxxxxxxxxxxx.loc
2020-09-08 15:50:51 SERVER -> CLIENT: 250-xxxxxxxx.[SERVER].com250-PIPELINING250-SIZE 102400000250-VRFY250-ETRN250-AUTH PLAIN LOGIN250-AUTH=PLAIN LOGIN250-ENHANCEDSTATUSCODES250-8BITMIME250 DSN
2020-09-08 15:50:51 CLIENT -> SERVER: AUTH LOGIN
2020-09-08 15:50:51 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2020-09-08 15:50:51 CLIENT -> SERVER: [credentials hidden]
2020-09-08 15:50:53 SERVER -> CLIENT: 535 5.7.8 Error: authentication failed: VXNlcm5hbWU6
2020-09-08 15:50:53 SMTP ERROR: Username command failed: 535 5.7.8 Error: authentication failed: VXNlcm5hbWU6
SMTP Error: Could not authenticate.
2020-09-08 15:50:53 CLIENT -> SERVER: QUIT
2020-09-08 15:50:53 SERVER -> CLIENT: 221 2.0.0 Bye
SMTP Error: Could not authenticate.
Message could not be sent. Mailer Error: SMTP Error: Could not authenticate.
I don't wan to hardcode the credentials. Any idea how to get rid of this error?
Here's the code:
// initiate phpMailer
$mail = new PHPMailer(true);
// see config file
$mailSenderName = $_ENV['MAILER_CONTACT_USERNAME'];
$masterPassword = $_ENV['MAILER_CONTACT_PASSWORD'];
$masterEmail = $_ENV['MAILER_CONTACT_EMAIL'];
$recipient = $_ENV['MAILER_CONTACT_RECIPIENT'];
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'xxxxxxx.[SERVER].com';
$mail->SMTPAuth = true;
$mail->Username = $masterEmail;
$mail->Password = $masterPassword;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 25;
//Recipients
$mail->setFrom('aaa#bbbbbbbbbbb.com', 'aabbcc');
$mail->addAddress('mmmmmmmmm#bbbbbbbbbbb.com');
// Content
$mail->isHTML(true);
$mail->Subject = 'Message Received (Contact Page)';
$emailbody =
'There is a new message from: <br>' .
'==================================== <br>' .
$senderName . '<br>' .
$senderEmail . '<br' .
'====================================' .
$message . '<br>' .
'====================================';
$mail->Body = $emailbody;
$mail->send();
// success, show thank you
$f3->reroute('/contact/thankyou'); //todo
} catch (\Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Thanks!
Debug one thing at a time. There's no point in looking at error in your email when you know you know you have a problem before it ever gets that far. PHPMailer uses whatever you give it, so you need to be sure you're giving it the right thing.
You could reduce the code to debug in this case by cutting it back to:
var_dump($_ENV);
Once you know that you're setting the contents of $_ENV correctly (whether from real env vars, from a dotenv script, your php.ini config, etc), you can then start using the values in your email code.
After installing dotenv (vlucas) I simply didn't include it correctly in my ContactController. So that's why var_dump($_ENV) always resulted in NULL. I compared my settings with the other route, NewsletterController. The difference is that in this route I query the database and in the models constructor (where the db connection is set) I 'use' the dotenv class correctly, and that's why the $_ENV is filled with data. I simply didn't see it.
So, in ContactController I set:
use \Dotenv;
and after initialising phpmailer I added:
$mail = new PHPMailer(true);
$dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
Difference to Models class (database connection):
namespace Models;
use \Dotenv;
abstract class Model
{
protected $db;
public function __construct()
{
$dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
$dotenv->load();
$this->db = new \DB\SQL(
'mysql:host='. $_ENV['DB_HOST'] .';port='.$_ENV['DB_PORT'].';dbname='.$_ENV['DB_NAME'],
$_ENV['DB_USERNAME'],
$_ENV['DB_PASSWORD']
);
}
}

Set TLS Version with Apache Httpclient and WebSphere Liberty Profile

We are accessing an external service from our WebSphere Liberty Profile (8.5.5.6) REST service which uses Apache HTTPClient 4.3.5 to connect to the service.
The service just changed to use TLS v1.2, and now our service is failing with:
[4/21/16 12:23:37:596 EDT] 0000005d bm.myw3.services.awf.sso.ejb.generator.SSOTokenGeneratorImpl I Exception :: javax.net.ssl.SSLException: Received fatal alert: protocol_version
[4/21/16 12:23:37:597 EDT] 0000005d com.ibm.myw3.services.awf.sso.ejb.SSOTokenManagerBean E SSOTokenGeneratorException :: {0}
com.ibm.myw3.services.awf.sso.ejb.config.SSOTokenGeneratorException: Exception while executing http request for retrieving Token
We found the following link, and implemented it in our code:
How to set TLS version on apache HttpClient
SSLContext sslContext = SSLContexts.custom().useTLS().build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
I have also set the 'https.protocols':
wasadmin 28548 1 10 12:28 pts/0 00:00:55 /usr/lib/jvm/jre-1.7.1-ibm.x86_64/bin/java -javaagent:/opt/IBM/WebSphere/Liberty/wlp/bin/tools/ws-javaagent.jar -Djava.awt.headless=true -XX:MaxPermSize=256m -Dcom.ibm.security.jurisdictionPolicyDir=/devops/w3Services/ssoProxy -Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1 -jar /opt/IBM/WebSphere/Liberty/wlp/bin/tools/ws-server.jar w3svcs-ssoproxy-svr1
But it is making no difference. Is there something else we need to do in order to get this to work with WLP?
We've tried some other things, and here is our latest iteration of the code:
SSLContext sslContext = SSLContexts.custom().useProtocol("TLSv1.2").build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" },
new String[] { "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
.setConnectionManager(connManager).setSSLSocketFactory(sslsf);
handleAuthentication(uri, httpClientBuilder);
httpClient = httpClientBuilder.build();
I am also setting the following JVM options:
JVM_ARGS=-Dhttps.protocols=TLSv1.2 -Djdk.tls.client.protocols=TLSv1.2 -Djavax.net.debug=all
But we are still getting the error:
[4/21/16 17:27:37:123 EDT] 00000042 id= bm.myw3.services.awf.sso.ejb.generator.SSOTokenGeneratorImpl I Exception :: javax.net.ssl.SSLException: Received fatal alert: protocol_version
[4/21/16 17:27:37:124 EDT] 00000042 id= com.ibm.myw3.services.awf.sso.ejb.SSOTokenManagerBean E SSOTokenGeneratorException :: {0}
com.ibm.myw3.services.awf.sso.ejb.config.SSOTokenGeneratorException: Exception while executing http request for retrieving Token
I have a trace.log from WLP, which I can upload if anyone thinks it would be useful to see. But here aer various entries from the trace:
Default Executor-thread-25, WRITE: TLSv1.2 Handshake, length = 80
Default Executor-thread-25, WRITE: TLSv1.2 Application Data, length = 256
Default Executor-thread-25, READ: TLSv1.2 Application Data, length = 1552
SEND TLSv1.2 ALERT:
Finalizer thread, WRITE: TLSv1.2 Alert, length = 64
And then it goes on to try TLSv1, which the service we're calling doesn't support anymore. I'm not sure what to look for to determine why it's not using TLSv1.2, but nothing is jumping out at me from the trace.
One cannot set a custom socket factory and a fully initialized connection manager at the same time when building an HttpClient instance. Method #setConnectionManager supersedes #setSSLSocketFactory.
Do either this
SSLContext sslContext = SSLContexts.custom().useProtocol("TLSv1.2").build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" },
new String[] { "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setSSLSocketFactory(sslsf);
or this
SSLContext sslContext = SSLContexts.custom().useProtocol("TLSv1.2").build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" },
new String[] { "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm);
Oh yes, one more thing. Please consider upgrading to 4.5

javax.mail.sendfailedexception sending failed nested exception is class javax.mail.MessagingException

It give error about some problem with STARTTLS command .
it gives the error like this
javax.mail.sendfailedexception sending failed nested exception is class javax.mail.MessagingException
So please help me out of it.
Java Code
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailDemo {
public static void main(String[] args) {
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");
Scanner scn=new Scanner(System.in);
System.out.println("Username for Authentication :");
final String username=scn.nextLine();
System.out.println("Password for Authentication :");
final String password=scn.nextLine();
System.out.println("From Email..");
String fromEmailAddrs=scn.nextLine();
System.out.println("To Email..");
String toEmail=scn.nextLine();
System.out.println("Subject..");
String subject=scn.nextLine();
System.out.println("Message..");
String textMessage=scn.nextLine();
Session session=Session.getDefaultInstance(properties,new Authenticator() {
#Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(username, password);
}
});
try{
Message msg=new MimeMessage(session);
msg.setFrom(new InternetAddress(fromEmailAddrs));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
msg.setSubject(subject);
msg.setText(textMessage);
Transport.send(msg);
System.out.println("/n Your Message Delivered Succesfully");
}
catch(MessagingException m){
throw new RuntimeException(m);
}
}
}
Console
Username for Authentication :
bijaybhaskar01
Password for Authentication :
abcdef#456789
From Email..
bijaybhaskar01#gmail.com
To Email..
bbswain1001#gmail.com
Subject..
Hello
Message..
hai
Output
Exception in thread "main" java.lang.RuntimeException: javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. fh14sm3131583pab.31 - gsmtp
at com.mail.bhaskar.MailDemo.main(MailDemo.java:52)
Caused by: javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. fh14sm3131583pab.31 - gsmtp
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at com.mail.bhaskar.MailDemo.main(MailDemo.java:48)
Debug output
DEBUG: JavaMail version 1.3.1
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.8.0_77\lib\javamail.providers (The system cannot find the file specified)
DEBUG: URL jar:file:/E:/Study/Java/Jars/MailJars/gimap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/E:/Study/Java/Jars/MailJars/gimap.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/E:/Study/Java/Jars/MailJars/imap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/E:/Study/Java/Jars/MailJars/imap.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/E:/Study/Java/Jars/MailJars/pop3.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/E:/Study/Java/Jars/MailJars/pop3.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/E:/Study/Java/Jars/MailJars/smtp.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/E:/Study/Java/Jars/MailJars/smtp.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.gimap.GmailSSLStore=javax.mail.Provider[STORE,gimaps,com.sun.mail.gimap.GmailSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.gimap.GmailStore=javax.mail.Provider[STORE,gimap,com.sun.mail.gimap.GmailStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], gimap=javax.mail.Provider[STORE,gimap,com.sun.mail.gimap.GmailStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], gimaps=javax.mail.Provider[STORE,gimaps,com.sun.mail.gimap.GmailSSLStore,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: URL jar:file:/E:/Study/Java/Jars/MailJars/smtp.jar!/META-INF/javamail.address.map
DEBUG: successfully loaded resource: jar:file:/E:/Study/Java/Jars/MailJars/smtp.jar!/META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.8.0_77\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587
220 smtp.gmail.com ESMTP n6sm3627811pfa.2 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587
EHLO Bhaskar
250-smtp.gmail.com at your service, [119.82.116.106]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<bijaybhaskar01#gmail.com>
530 5.7.0 Must issue a STARTTLS command first. n6sm3627811pfa.2 - gsmtp
QUIT
You're using JavaMail 1.3.1, which is ancient and does not support STARTTLS.
Upgrade to a newer version.

How to send mails from Java mail API from a server not having internet connection and using web server?

I am using JAVA mail API to send mails and using SMTP. When I am putting the code in the test server it is successfully sending mails as it is having internet connection. But in the production there is no internet connection. Is it possible to send mails using the web server? The code that I am using to send mails is as follows.
final String username = "momkutty#gmail.com";
final String password = "password";
Properties props = new Properties();
System.out.println("Setting properties");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.google.com");
props.put("mail.smtp.port", "25");
System.out.println("Properties set successfully");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
System.out.println("Setting message properties");
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("momkutty#gmail.com"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("sumankalyan.roy#cmcltd.com"));
message.setSubject("Test Subject");
message.setText("Hey!!!! This is a TEST mail using SMTP SMTP port no.25.....");
System.out.println("Going to send mail...");
Transport.send(message);
System.out.println("Mail has been Sent");
} catch (MessagingException e) {
e.printStackTrace();
}
}e
If you have a SOCKS proxy server, see this JavaMail FAQ entry.
If you only have a web proxy server, you might need something like corkscrew.
I am using my web server IP as "socksProxyHost" and 1080 as "socksProxyPort"...!! refer the following lines....!
props.setProperty("proxySet","true");
props.setProperty("socksProxyHost","10.10.30.146");
props.setProperty("socksProxyPort","1080");
and trying to send mails through port no. 587...!!
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
but it says..
javax.mail.MessagingException: Could not connect to SMTP host: smtp.office365.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.cmcltd.vtms.sms.smsalert.SmsEmailAlerts.testMail(SmsEmailAlerts.java:1029)
at com.cmcltd.vtms.sms.smsalert.ScheduleJob.execute(ScheduleJob.java:25)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:534)
Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
... 10 more
Is it because the 587 port is blocked in the web server? Or there is something wrong in the code...!!?