JavaMail and Hotmail not working on Android - smtp

I am having trouble sending emails from a hotmail address using JavaMail. I verified that I can connect to smtp.live.com via telnet port 587. The interesting thing (to me) is if I change:
host = "smtp.gmail.com"
t.connect(host, username, password);
It connects to Gmail just fine on the default port and sends an email.
But if I change the code to:
host = "smtp.live.com"
t.connect(host,587, username, password);
It gives me the following error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.live.com, port: 587;
nested exception is:
java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:604 0xaf076228:0x00000000)
With session.setDebug(true) I get this info:
09-15 01:57:37.280: INFO/System.out(720): DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1]
09-15 01:57:37.300: INFO/System.out(720): DEBUG SMTP: useEhlo true, useAuth true
09-15 01:57:37.310: INFO/System.out(720): DEBUG SMTP: trying to connect to host "smtp.live.com", port 587, isSSL true
09-15 01:57:37.330: INFO/SSLSocketFactory(720): Using factory org.apache.harmony.xnet.provider.jsse.OpenSSLSocketFactoryImpl#4007ed70
09-15 01:57:37.490: DEBUG/NativeCrypto(720): SSL_OP_NO_SSLv3 is set
09-15 01:57:37.538: ERROR/NativeCrypto(720): Unknown error 1 during connect
Looks like Hotmail isn't playing nice with OpenSSL. Does anyone have a solution for this?
Below is my code in...just in case it helps.
Thanks in advance,
J
String host = "smtp.live.com";
String username = foo#hotmail;
String password = "**";
Transport t = null;
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props);
session.setDebug(true);
try{
MimeMessage msg = new MimeMessage(session);
msg.setSubject("Testing SMTP-SSL");
msg.setContent("This is a test", "text/plain");
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(username, false));
t = session.getTransport("smtps");
t.connect(host,587, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
t.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

I had the same problem with sending emails to Hotmail/Outlook...
I solved it by adding the socket factory port always to 578 in your properties like:
props.put("mail.smtp.socketFactory.port", "587");
and for hotmail case the port is 25.
props.put("mail.smtp.port", "25");
A bit late but maybe it helps ;)

Related

Why is TcpClient.Connect() throwing System.AggregateException

I am trying to check the TCP connection to a localhost TCP server (ActiveMQ broker) using following code:
string host = "localhost";
int port = 61616;
using (TcpClient tcpClient = new TcpClient())
{
try
{
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
Console.WriteLine("Connected.");
TimeSpan ts = TimeSpan.FromMilliseconds(150);
if (!t.Wait(ts))
{
Console.WriteLine("The timeout interval elapsed.");
Console.WriteLine("Could not connect to: {0}", port);// ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString());
}
else
{
Console.WriteLine("Port {0} open.", port);
}
}
catch (UnauthorizedAccessException )
{
Console.WriteLine("Caught unauthorized access exception-await behavior");
}
catch (AggregateException )
{
Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
}
I stopped the localhost server (ActiveMQ broker), and tried to run the above code. It threw System.AggregateException. When I started the server and ran the code; it connects to the server.
According to the documentation of TcpClient.Connect it says it will throw one of the following:
ArgumentNullException
ArgumentOutOfRangeException
SocketException
ObjectDisposedException
SecurityException
NotSupportedException
Why will it throw System.AggregateException?
This
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
wraps your .Connect() call. And Task.Run() always throws AggregateException with the real exception inside it. In order to fix this either inspect the exception or even better use the asynchronous variant of .Connect():
Task t = tcpClient.ConnectAsync(host, port);
instead.
What i did finally is:
tcpClient.ReceiveTimeout = 5000;
tcpClient.SendTimeout = 5000;
tcpClient.Connect(host, port);
catch (SocketException) {
Console.WriteLine("Could not connect to: {0}", port);
Console.WriteLine("Socket exception. Check host address and port.");
}
It seems to be working.

Not getting any response from smtp server

I am trying to sent a mail through following java code.
Properties props = new Properties();
props.put("mail.host",mailProperties.get("mail.smtp"));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
final PasswordAuthentication pauth;
pauth = new PasswordAuthentication(""+mailProperties.get("mail.user"),""+mailProperties.get("mail.pwd"));
class MyAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return pauth;
}
}
Authenticator auth = new MyAuthenticator();
Session mail = Session.getInstance(props,auth);
mail.setDebug(true);
Message msg = new MimeMessage(mail);
Transport.send(msg);
But not being able to send mail,
only output I am getting is as follows :
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG: SMTPTransport trying to connect to host "mail.bizsolindia.com", port 465
While trying to check with telnet I am getting the response as shown in screen shot.
Kindly suggest any correction required from my side.

SendGrid SMTP error {"Unable to read data from the transport connection: net_io_connectionclosed."}

This might seem to be duplicate but it is not. I tried restarting the IIS, enclosing the SMTPClient in the using block etc. But Still I'm getting the error.
try
{
//I have replaced sender#gmail.com and receiver#gmail.com by a valid gmail addresses
MailAddress sender = new MailAddress("sender#gmail.com");
MailAddress receiver = new MailAddress("receiver#gmail.com");
MailMessage mailMsg = new MailMessage(sender, receiver);
mailMsg.Subject = "subject";
string text = "text body";
string html = #"<p>html body</p>";
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
using(SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Host = "smtp.sendgrid.net";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
//UserName = Username of SendGrid account, Password = Password of SendGrid account
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("UserName", "password");
smtpClient.Credentials = credentials;
smtpClient.ServicePoint.MaxIdleTime = 1; /* without this the connection is idle too long and not terminated, times out at the server and gives sequencing errors */
smtpClient.Send(mailMsg);
}
}
catch (SmtpException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
This is a MVC application developed in VS 2015.
Any input on this will be helpful.
In my case, I didn't notice I had put the wrong username in the web.config settings
You can see SendGrid configuration for SMTP by going to Setup -> Guide -> Integrate SMTP after login into https://app.sendgrid.com

Failed to send certificate after upgrading to latest windows phone 8.1

I have a Windows Phone App, built for 8.1, and one of the tasks was a client-server certificate scenario. My app worked fine, I could send the client certificate and login to the server. However after upgrading to windows 8.10.14xxxx that was not possible. I took wireshark traces and it seems that the certificate is never send.
The content length of the message is 0.
I use HttpClient.SendAsync (await) and HttpBaseProtocolFilter to enter the certificate. It worked perfect before the upgrade.
Any idea? Is something broken?
First I am installing the pfx
async private void btnInstall_Click(object sender, RoutedEventArgs e)
{
//Install the self signed client cert to the user certificate store
string CACertificate = null;
try
{
Uri uri = new Uri("ms-appx:///certificates/test.pfx");
var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
IBuffer buffer = await FileIO.ReadBufferAsync(file);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
byte[] bytes = new byte[buffer.Length];
dataReader.ReadBytes(bytes);
// convert to Base64 for using with ImportPfx
CACertificate = System.Convert.ToBase64String(bytes);
}
await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync(
CACertificate,
"xxxxx",
ExportOption.Exportable,
KeyProtectionLevel.NoConsent,
InstallOptions.None,
"ClientCert1");
}
catch (Exception ex)
{
//;
}
}
Then I am calling the service
string serviceURL = "https://my.web.services";
Certificate cert = null;
CertificateQuery query = new CertificateQuery();
query.FriendlyName = "ClientCert1";
IReadOnlyCollection<Certificate> certs = await CertificateStores.FindAllAsync(query);
HttpBaseProtocolFilter bpf = new HttpBaseProtocolFilter();
//if you install the CA you don't need to ignore the ServerCertificate Errors
//bpf.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
if (certs.Count > 0)
{
cert = certs.ElementAt(0);
bpf.ClientCertificate = cert;
}
HttpClient httpClient = new HttpClient(bpf);
try
{
var response = await httpClient.GetInputStreamAsync(new Uri(serviceURL));
//take data
}
catch (Exception ex)
{
//0x80072F0D
}
I am always taking an excepting (0x80072F0D) when running in 8.10.14xxxx windows phone. My code worked before the update, now I am always taking this return code. The certificate is loaded in httpClient. When I stop the app with the debugger it seems that the certificate is there, however the 0x800072F0D probably means that the certificate is not sent???
There is an intermediate certificate authority in the scenario. That certificate is included in the pfx. Do I need to install this somehow?
I am assuming that you have already put the client certificate in app certificate store.
If not then do these:
1) Download the PFX file.
2) Install certificate in the App's certificate store by following
await CertificateEnrollmentManager.ImportPfxDataAsync(certString, "Your_PFX_Password", ExportOption.Exportable, KeyProtectionLevel.NoConsent, InstallOptions.None, friendlyName);
3) Check for the certificate in certificate store.
CertificateQuery certQuery = new CertificateQuery();
certQuery.FriendlyName = friendlyName;
IReadOnlyList<Certificate> certs = await CertificateStores.FindAllAsync(certQuery);
The certs[0] should have the certificate that you need.
4) Now, to attach the certificate to HTTP request
HttpBaseProtocolFilter protolFilter = new HttpBaseProtocolFilter();
protolFilter.ClientCertificate = certs[0] //from previous step
HttpClient client = new HttpClient(protolFilter)
PS : You should not use System.Net.htpp.HttpClient. Instead of that you should use Windows.Web.Http.HttpClient.

getting mails via gmail using javamail over SSL and POP3

In fact I am trying to get emails through Gmail POP3, I enabled POP3 protocol in gmail but established a session and connection over SSL but I am an exception and unable to figure it out what is the actual matter behind.
here is the exception
Exception in thread "main" javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:382)
at javax.mail.Service.connect(Service.java:226)
at javax.mail.Service.connect(Service.java:246)
at EmailReciever.getEmail(EmailReciever.java:47)
at TestEmailReceiver.main(TestEmailReceiver.java:14)
and the I connected it as like
public void getEmail(String host, String port, final String userName, final String password)
throws MessagingException, IOException {
// sets POP3 properties
Properties properties = new Properties();
properties.put("mail.pop3.com", host);
properties.put("mail.pop3.port", port);
properties.put("mail.pop3.auth", "true");
// sets POP3S properties
properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port", "995");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
please help!
here is my debugging output...
DEBUG: setDebug: JavaMail version 1.5.0
DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]
DEBUG POP3: mail.pop3.rsetbeforequit: false
DEBUG POP3: mail.pop3.disabletop: false
DEBUG POP3: mail.pop3.forgettopheaders: false
DEBUG POP3: mail.pop3.cachewriteto: false
DEBUG POP3: mail.pop3.filecache.enable: false
DEBUG POP3: mail.pop3.keepmessagecontent: false
DEBUG POP3: mail.pop3.starttls.enable: false
DEBUG POP3: mail.pop3.starttls.required: false