Unknow SMTP host android JavaMail - java

I have a Mailserver, which is hosted at the same network as my phone, but I keep getting an exception saying Unknow SMTP host. I've read several places that this exception occurs when the hostname isnt correct spelled, of course. But in this case it IS. In C# its done a simple way like this:
var client = new SmtpClient(_strSmtpHost);
client.UseDefaultCredentials = true;
var mailMessage = new MailMessage(_strFrom, emailTo);
mailMessage.Subject = subject;
mailMessage.Attachments.Add(attachment);
client.Send(mailMessage);
And in my application its done this way:
SendMail m = new SendMail("Username", "password");
String[] toArr = {"TO#EXAMPLE.com"};
m.setTo(toArr);
m.setFrom("FROM#EXAMPLE.com");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment(fileName);
if(m.send()) {
Log.i("MAIL SENDER: ", "Succesfully");
} else {
Log.i("MAIL SENDER: ", "UnSuccesfully");
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email" + e);
}
In my SendMail class I define a String containing the DNS address of the host
_host = "napserver"; // default smtp server
_port = "25"; // default smtp port
Before I try to do a connect, I want to Authenticate username and password for the mail-address sending the mail:
Session session = Session.getInstance(props, new GMailAuthenticator(_user, _pass));
and then trying to a connect and send message
Transport transport = session.getTransport("smtp");
transport.connect(_host, 25, _user, _pass);
Transport.send(msg);
Just for testing purposes I tried the SMTP address for Gmail, and this worked, and the mail was sent to the specified mail account. Can anybody give me a hint?
EDIT
I should also mention that I tried to connect via Telnet to this mail server, and the ouput from PuTTy, when connected with the host napserver and port 25 :
220 napserver.nap01.dac.no.eu-admin.net Microsoft ESMTP MAIL Service, Version: 6 .0.3790.3959 ready at Tue, 7 Aug 2012 13:38:55 -0700
EDIT 2
As you can see from the PuTTy output:
Microsoft ESMTP MAIL Service
My mailserver uses the ESMTP, but as far as I know this just implements some security layers and so on. Maybe this is where the error is?
EDIT 3
I tried to access the mailserver via remote desktop, I pinging my phones IP-address just to be sure that the server and the phone is located on the same network, and it is..

Related

How to check mailserver supports TLS or Not

I want to check whether mailserver support TLS encryption or not using javamail.
I can able to check via terminal in Linux OS.
>> dig +short gmail.com mx
20 alt2.gmail-smtp-in.l.google.com.
10 alt1.gmail-smtp-in.l.google.com.
5 gmail-smtp-in.l.google.com.
40 alt4.gmail-smtp-in.l.google.com.
30 alt3.gmail-smtp-in.l.google.com.
>> telnet gmail-smtp-in.l.google.com 25
220 mx.google.com ESMTP c90si10657664pfd.233 - gsmtp
>>ehlo gmail.com
250-mx.google.com at your service,
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
250 STARTTLS then that email server is configured to support use of TLS.
In the same way, how we can do it using javamail programmatically?
Please help.
Do you really need just "yes, the server supports it" or "no, it does not support it"? Or you have to send an email and want to send it only if you can do it securely?
If it is the former you can just do what telnet does and do not bother using javamail.
If it is the later you can configure javamail to fail if the server does not support TLS.
See An SMTP protocol provider for the JavaMail API for details. Property 'mail.smtp.starttls.required' is what you need.
how would a java "yes, the server supports it" check for tls look like?
The only way i actual see is to make an dns lookup (e.g. via javax.naming.directory.InitialDirContext).
And then connect via telnet (e.g. via apache telnet client)
and parse the
You can query the server with java / jakarta mail using EHLO commands.
The following method queries the server for the support of TLS. No email is send. Other properties could be added. Of course ehlo must be enabled (mail.smtp.ehlo=true)
boolean detectTls(String smtpServerHost, int smtpServerPort, String smtpUserName, String smtpUserAccessToken) {
Transport transport = null;
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", smtpServerPort);
Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
transport = session.getTransport();
transport.connect(smtpServerHost, smtpServerPort, smtpUserName, smtpUserAccessToken);
if(transport instanceof SMTPTransport) {
return ((SMTPTransport)transport).supportsExtension("STARTTLS");
}
return false;
}
catch (Exception ex) {
//Proper loggin & exception handling!!!
//return false;
}
finally {
if(transport!=null) {
try {
transport.close();
}
catch (MessagingException e) {
}
}
}
}

Sending mail error, javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;

Here is my code
import java.util.Properties;
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 MailSendClass {
public static void main (String [] args){
// Recipient's email ID needs to be mentioned.
String to = "abc82#gmail.com";
// Sender's email ID needs to be mentioned
String from = "xyz#gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Thanks for registering on our website!");
// Now set the actual message
message.setText("Welcome To Job Portal !!!! Again Thanks ");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
And I am getting this error everytime
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1706)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at MailSendClass.main(MailSendClass.java:58)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1672)
... 7 more
BUILD SUCCESSFUL (total time: 3 seconds)
I am not getting the error why this is happening. Please help me in fixing this error.
Error is self explainatory: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
You have no SMTP server on localhost, but you configure it there :
// Assuming you are sending email from localhost
String host = "localhost";
...
// Setup mail server
properties.setProperty("mail.smtp.host", host);
So you must:
either configure a local SMTP server as a relay on your local system (Postfix or sendmail are two well knows servers)
of configure a dummy server that simply traces the mail request but does not even try to deliver mail (Python is known to have such dummy servers out of the box)
or configure your application with a server that you are allowed to use - contact your system admin in a corporate environment, or your ISP in an individual one. Anyway, you will need that even to configure a true relay.
Here is the working solution bro. it's guranteed
1) First of all open your gmail account from which you wanted to send mail, like in you case ""xyz#gmail.com"
2) open this link below
https://support.google.com/accounts/answer/6010255?hl=en
3) click on "Go to the "Less secure apps" section in My Account." option
4) Then turn on it
5) that's it (:
You should use the free Google SMTP server as a test.
mail.host=smtp.gmail.com
mail.username=//your gmail
mail.password=//your password
mail.defaultEncoding=UTF-8
mail.smtp.auth=true
mail.smtp.starttls.required=true
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false
mail.smtp.port=465
mail.smtp.socketFactory.port=465
Next, login with your gmail , and turn on less secure apps.
You should look at this two lines:
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
Caused by: java.net.ConnectException: Connection refused: connect
The error is: "There is nothing listening on localhost at port 25".
You are trying to use localhost:25 as mail server, but there is no server there.
Just use this provided solution : javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
and make sure to turn on less secure app access on your google account.

Not Receiving email sent by localhost Mercury mail

I am using XAMPP for deploying my java application in tomcat and also using mercury mail to ssend emails. Now i am just testing my application with a small java program using java mail API and mercury email. I havee done the necessary configuration in Mercury to setup localhost. My program is running successfully without any error. Also Mercury log file doesn't say anything about any error.
T 20130411 044359 51663963 Connection from 127.0.0.1
T 20130411 044359 51663963 EHLO 10.226.44.101
T 20130411 044359 51663963 MAIL FROM:<promil#localhost.com>
T 20130411 044359 51663963 RCPT TO:<*****#gmail.com>
T 20130411 044359 51663963 DATA
T 20130411 044359 51663963 DATA - 22 lines, 689 bytes.
T 20130411 044359 51663963 QUIT
T 20130411 044359 51663963 Connection closed with 127.0.0.1, 0 sec. elapsed.
Also this is my java file....
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "****#gmail.com";
// Sender's email ID needs to be mentioned
String from = "promil#localhost.com";
// Assuming you are sending email from localhost
String host = "localhost";
String password = "****";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Setup mail server
properties.setProperty("mail.smtp.password", password);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/toshiba/Desktop/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
I am absolutely clueless about it.....
Also my Mercury core process says it has 4 pending outgoing jobs....???
The destination address is at gmail. You haven't clarified if the mail was supposed to be delivered locally or at gmail, so I'm going to assume you meant the mail to go to a Gmail account, which you've (correctly) obfuscated in your post.
The session transcript you posted is between your Java client and the local Mercury mail server. All this says is that the local Mercury mail server accepted the mail from your Java client.
The session transcript contains no information about what happened to the mail after your local Mercury mail server accepted it. If the local configuration was correctly set up, then Mercury mail should have tried to forward the mail by looking up the MX record for Gmail and connecting to one of the servers returned by the MX lookup.
For further information you will have to look at the Mercury server's logs to see if it attempted to deliver the message.
A guess:
Your Mercury mail server attempted to deliver the mail, but Gmail rejected it because the computer you are running on has an ISP-assigned DHCP (dynamic) address. A large volume of SPAM originates from such addresses, and many mail hosts refuse to even talk to these mail sources. In any event, if Gmail rejected it, Mercury mail is required to "bounce" it back to the sender. However, you probably have not set up an incoming mailbox for promil#localhost.com, so it had no place to store the bounce and just discarded it. Again, check the Mercury mail logs for details.
That's the best answer anyone can give based on the information you have provided.

JavaMail to send email through vps, require NO authentication, but get AuthenticationFailedException - why?

I originally setup my site to use my local ISP to send email through my site. I would like to change this, and start sending email through my VPS. According to the online documentation (from my vps provider) I have "POP before SMTP authentication". So then, I do not require authentication nor do I require a secure connection at this time.
I changed a few things in the code I used for sending email through my local ISP. Here's what I have :
Transport t = null;
try {
String Username = "mrsmith#mydomain.com";
String Password = "somepassword";
InternetAddress from = new InternetAddress("mrsmith#mydomain.com", "Bob Smith");
Properties props = new Properties();
//commented out, since I don't want to use authentication
//props.setProperty("mail.smtp.auth", "true");
props.put("mail.pop3.host", "mydomain.com";
props.put("mail.smtp.host", "mydomain.com");
String protocol = "smtp";
Session ssn = Session.getInstance(props, null);
ssn.setDebug(true);
t = ssn.getTransport(protocol);
Store s = ssn.getStore();
s.connect();
t.connect(SMTP,Username,Password);
//Create the message
Message msg = new MimeMessage(ssn);
msg.setFrom(from);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setContent(body, "text/html");
t.sendMessage(msg, msg.getAllRecipients());
t.close();
s.close();
I contacted my vps provider and after following their instructions, in tweaking the code, I still get "Authentication Failed". This after a successful connection has been made to the host on port 25.
Can someone point out what it is I'm missing here?
Editing to add additional information
After I added the store.connect("mailhost",Username,Password); statement to the code, I got further than ever before!
Here is some info that was printed to the tomcat prompt -
DEBUG : getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc.]
POP3: connecting to host "mydomain.com", port 110, isSSL false
server ready
OK User name accepted, password please
Password somepassword
OK Mailbox open, 0 messages
DEBUG: geProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smpt.SMTPTransport,Sun Microsystems, Inc.]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "mydomain.com", port 25, isSSL false
220 mydomain.com ESMTP Sendmail 8.14.3/8.14.3; DEC 2010 29
DEBUG SMTP: connected to host "mydomain.com", port: 25
( a lot of additional debug information was here )
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
535 5.7.0 authentication failed
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:319)
at javax.mail.Service.connect(Service.java:169)
... continues with more 'at's.
Do you see anything odd in this information? I don't quite understand why the authentication failed while the Pop3 was authenticated with the same username and password.
POP before SMTP authentication basically means you need to be able to prove that you can fetch your mail using POP3 (using proper authentication) before you will be allowed to send mail using SMTP (without authentication).
Using the Java Mail API, you can do the authentication to the POP3 server like this :
Store store = ssn.getStore("pop3");
store.connect("mailhost", Username, Password);
You should execute these calls prior to connecting to the SMTP server, so before connecting to the SMTP server (without username and password) like this
t.connect();
make sure you connect to the store first.
In your snippet, you are still authenticating against the smtp as you are providing a username/password.
Another option is to use Commons Email, that has built-in support for pop before smtp authentication. Check out the following method in http://commons.apache.org/email/apidocs/org/apache/commons/mail/Email.html
email.setPopBeforeSMTP(true,popHost,popUsername,popPassword);
Using commons email, there's no need to do the pop plumbing in your code (connecting prior to sending).
Properties props = new Properties();
props.put("mail.smtp.host", "mailserver.com");
Session s = Session.getInstance(props,null);
InternetAddress from = new InternetAddress("mail#mail.com");
InternetAddress to = new InternetAddress(recepeint#server.com");
For more information please visit:
http://www.itpian.com/Coding/314-SENDING-EMAILS-THROUGH-JAVAMAIL.aspx
Check if provider implementation(pop3.jar) is in your buildpath/classpath.

Unable to send mail from Java application

In my java application I need to send mails to different mail addresses. I am using the next piece of code , but for some reason it doesn't work.
public class main {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "mail.yahoo.com.");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
Session session = Session.getInstance(props, new MyAuth());
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("giginnho#yahoo.com"));
InternetAddress[] address = {new InternetAddress("rantravee#yahoo.com")};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("subject ");
msg.setSentDate(new Date());
msg.setText("Message here ");
Transport.send(msg);
} catch (MessagingException e) {}
}
}
class MyAuth extends Authenticator {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("my username","my password");
}
}
I get the folowing text from debuging it:
[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.mail.yahoo.com.au.", port 25, isSSL false
Could anyone inform me , what I am doing wrong here ?
Yahoo! Mail SMTP server address: smtp.mail.yahoo.com
Yahoo! Mail SMTP user name: Your full Yahoo! Mail email address (including "#yahoo.com")
Yahoo! Mail SMTP password: Your Yahoo! Mail password
Yahoo! Mail SMTP port: 465
Yahoo! Mail SMTP TLS/SSL required: yes
Similar settings work with gmail. For yahoo you might need yahoo plus account
I am not sure, but I faced the same problem when sending mail using a gmail id, you are using yahoo. The problem was gmail uses ssl layer protection, i think same is the case with yahoo so you need to use
mail.smtps.host instead of mail.smtp.host
and same for other properties too.
and isSSL to true.
I can post complete code snippet, once i reach office and use office's machine. For now you can look at http://www.rgagnon.com/javadetails/java-0570.html
It could be an issue with your ISP blocking port 25 traffic (not unusual!)
From http://help.yahoo.com/l/us/yahoo/smallbusiness/bizmail/pop/pop-32.html:
In an attempt to control unsolicited email (spam), some Internet service providers now block port 25, which means you could experience technical problems when sending email. If you are having trouble sending email, you may need to use port 465 (recommended) or 587 when sending email via Yahoo!'s SMTP server.

Categories