How to send email in java GWT - java

I am using this code in my java GWT application
public String greetServer(String input) throws Exception {
try{
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.host", "smtp.random.com");
props.setProperty("mail.user", "foo#bar.com");
props.setProperty("mail.password", "000000000");
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("hello");
message.setContent("helloo sss", "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress("junaidp#gmail.com"));
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch(NoSuchProviderException e){
throw new Exception(e);
}
return input;
}
Error: javax.mail.MessagingException: Could not connect to SMTP host: smtp.random.com, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
if i use
props.setProperty("mail.host", "smtp.live.com");
and use my hotmail account , it gives this error
javax.mail.MessagingException: can't determine local email address
Any idea what could be the solution
thanks

I just used Simple Java Mail in a GWT project. You might want to try it. It's very simple to configure.
There are lots of example there, including one of sending using gmail's SMTP server using for example TLS:
Email email = new Email.Builder()
.from("Michel Baker", "m.baker#mbakery.com")
.to("mom", "jean.baker#hotmail.com")
.to("dad", "StevenOakly1963#hotmail.com")
.subject("My Bakery is finally open!")
.text("Mom, Dad. We did the opening ceremony of our bakery!!!")
.build();
new Mailer("smtp.gmail.com", 25, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 587, "your user", "your password", TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com", 465, "your user", "your password", TransportStrategy.SMTP_SSL).sendMail(email);
If you have two-factor login turned on, you need to generate an application specific password from your Google account.

Here's some Gmail settings which work for me:
//these are fed into the Properties object below:
mail.smtp.starttls.enable = true
mail.transport.protocol = smtp
mail.smtp.auth = true
and some Java:
Properties properties = ...
javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, password);

Error: javax.mail.MessagingException: Could not connect
to SMTP host: smtp.random.com port: 25;
nested exception is: java.net.ConnectException: Connection refused: connect
This error means that your SMTP server you provided is invalid. The code you have is correct, but smtp.random.com must not be a valid SMTP server.
I suggest you look into using Google's SMTP server that is free provided you use a valid gmail account.
Refer to this page for more information on using Gmail's STMP server: http://email.about.com/od/accessinggmail/f/Gmail_SMTP_Settings.htm

This tutorial worked for me in the past

Related

Sending email through proxy using gmail smtp JAVA

I'm trying to send a email in Java, I'm using a server proxy.
I've specified the proxy settings like that but doesn't works.
Properties props = System.getProperties();
props.put("http.proxyHost", "192.168.20.2");
props.put("http.proxyPort", "321");
props.put("java.net.useSystemProxies", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("asdf#gmail.com"));
message.setSubject("SUBJECT");
message.setText("BODY");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", sender,pass); //exception here!!!
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (MessagingException me) {
me.printStackTrace();
}
And I'm getting this exception because the code doesn't connect to internet.
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
Somebody knows why the program isn't taking the specified proxy?
I assume you're using JavaMail?
If that's the case, you probably are using the wrong properties, there are different ways to configure it depending on your proxy's authentication and JavaMail version you're using: https://javaee.github.io/javamail/FAQ.html#proxy

SMTP Mail Sending Issue : com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay

I am trying to send mail from Java.
If i will send mail to same SMTP it working fine.
If i will send mail to outside SMTP means like Gmail, Yahoo etc. it'as shows error like,
[com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay][1]
ERROR :
SimpleEmail Start
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
Mail Send Successfully
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:2064)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1286)
at javax.mail.Transport.send0(Transport.java:255)
at javax.mail.Transport.send(Transport.java:124)
at com.nirav.java.project.demo.JavaMailSend.sendEmail(JavaMailSend.java:26)
at com.nirav.java.project.demo.NewSimpleMail.main(NewSimpleMail.java:34)
Caused by: com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1917)
... 5 more
Code For Mail Sending :
try {
System.out.println("SimpleEmail Start");
String smtpHostServer = "XX.XX.XX.XXX";
final String toEmail = "XXXXXXXXXX#XXX.XXX";
final String fromEmail = "XXXXXXXXXX#XXX.XXX";
final String password = "XXXXXXXXXXXX";
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHostServer);
props.put("mail.smtp.port", "25"); //If other then
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
//Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.addHeader("Content-type", "text/HTML; charset=UTF-8");
message.addHeader("format", "flowed");
message.addHeader("Content-Transfer-Encoding", "8bit");
message.setFrom(new InternetAddress("XXXXXX#XXX.XXX", "NoReply-JD"));
message.setReplyTo(InternetAddress.parse("XXXXXXXXX#XXX.XXX", false));
message.setSubject(subject, "UTF-8");
message.setText(body, "UTF-8");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
Transport.send(message);
System.out.println("Mail Send Successfully");
} catch (Exception e) {
e.printStackTrace();
}
Please help me.
Thnaks.
Originally I was about to post this as comment, but it's too long.
The error is quite obvious, you are not allowed to use given SMTP server as relay. (What are SMTP relays?)
There are couple of reasons why this can happen:
You are not authenticated (need to login before sending)
Recipient is not in list of domains allowed to relay to
IP address from which you are connecting is not in white list (aka mynetworks in postfix context)
without providing more info (which SMTP server you are using, where are you sending mail, are you authenticated), I guess nobody will help you.
5.7.1 status code from IANA registry
The sender is not authorized to send to the destination. This can be
the result of per-host or per-recipient filtering. This memo does not
discuss the merits of any such filtering, but provides a mechanism to
report such. This is useful only as a permanent error.
Had this problem also but it was intermittent.
We have 2 servers that are within a cluster and on one the ip address of system that sends the email was not defined correctly.
Unfortunately the error message "javax.mail.SendFailedException: Invalid Addresses is confusing.
the 2nd error message: "com.sun.mail.smtp.SMTPAddressFailedException: 550 relay not permitted" matches much better.

How to solve: Sending the email to the following server failed SocketException: Permission denied: connect

I am facing issue while sending mails programmatically using Java. I confirmed from the network team that sending mails through Java is blocked using firewall.
but am able to get the response from telnet in my windows command prompt. Please find the details below.
Code used to send mail using Javax Mail:
public static void main(String[] args) throws MessagingException {
String host = "mailhost.xxx";
String to = "abc#xyz.edu";
String from = "cde#xyz.edu";
String subject = "test";
String messageText = "body test";
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", "25");
// If using authentication, otherwise comment out
props.put("mail.smtp.auth", "true");
// Gmail requires TLS, your server may not
props.put("mail.smtp.starttls.enable", "true");
// Session mailSession = Session.getDefaultInstance(props, null);
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
// connect with authentication
// transport.connect(host,"myUsername" , "myPassword");
// connect without authentication
transport.connect();
transport.sendMessage(msg, address);
transport.close();
System.out.println("Mail was sent to " + to);
System.out.println(" from " + from);
System.out.println(" using host " + host + ".");
}
Using Telnet am able to send mails in command prompt:
telnet mailhost.xxx 25
am getting the response like:
220 mailhost Microsoft ESMTP MAIL Service ready at Tue, 29 Mar 201
6 23:34:36 -0700
After googling I also tried setting JVM argument in Eclipse as below, no luck still getting the exception as shown below
-Djava.net.preferIPv4Stack=true
Exception:
Exception in thread "main" org.apache.commons.mail.EmailException: Sending the email to the following server failed : mailhost.xxx:25
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
at org.apache.commons.mail.Email.send(Email.java:1267)
at edu.xxx.pageobject.appcenter.util.ReportGenerator.main(ReportGenerator.java:328)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: mailhost xxx, port: 25;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
... 2 more
Caused by: java.net.SocketException: Permission denied: connect
at java.net.TwoStacksPlainSocketImpl.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.PlainSocketImpl.connect(PlainSocketImpl.java:172)
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:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 9 more
Let me know any possible solution to resolve the above issue.
Since :
the source exception points to a permissions issue,
but you can connect from command line using telnet
that's not a network firewall issue.
You also ruled out the related Java 7 bug.
So, the problem probably comes from your local Windows Firewall, or whatever Antivirus/firewall you're using. It may grant permissions to telnet, but not to Java.
Try to disable all your local firewall/antivirus, and check if java can successfully connect. If so, re-enable your firewall, and create an exception rule to allow connections to port 25 for your Java application.
Posting an alternate solution for my above issue:
As we were using Exchange accounts we were able to send the mails programmatically using EWS (Exchange Web Services) API.
EWS Getting Started Guide Link

Send Java email without authentication (no such provider exception: smtp)

The code I am currently using is as follows:
String to = "....#gmail.com";
String from = ".....#gmail.com";
String host = "127.0.0.1";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
If I paste the above code in my Java servlet and run it, the following exception gets thrown:
javax.mail.NoSuchProviderException: smtp
I have also tried following the solutions outlined in these resources but to no avail: link1 link2 link3 link4.
It would help if you included the the full stacktrace for the javax.mail.NoSuchProviderException and JavaMail debug output. Because you are running this in a servlet container you could be running into Bug 6668 -skip unusable Store and Transport classes. Change your call to Transport.set to the following:
final ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
try {
Transport.send(message);
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
That code will isolate which transport class the code is allowed to see. That will rule out that bug in your code.
NoSuchProviderException means something is messed up in your JavaMail API configuration. Where and how have you installed the JavaMail jar file?
Also, in case it's not clear from the other responses, the only way you're going to be able to send mail without authentication is if you're running your own mail server. You can't do it with general purpose online e-mail services (e.g. Gmail).
First of all, if you wanna use gmail to send emails from your program you need to define stmp host as gmail. Your current host "127.0.0.1" is localhost meaning your own computer? Do you have mail server running on your computer?
Here you can see some tutorial how to send an email using gmail: http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
If you're afraid to pass your normal gmail account details then create some kind of test email like kselvatest or something.
You are missing pretty much those:
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
So basicly all you need to add is:
1.login and password so JavaMail can use some gmail account
2.declare which mail server you wanna use
change String host = "127.0.0.1"; to String host = "smtp.gmail.com";
3.set mail port
For this code you should get javax.mail.MessagingException: Could not connect to SMTP host: 127.0.0.1, port: 25; exception
But I suspect you have a jre issue. May be smtp implementation has a problem. Why don't you download java mail implementation from http://www.oracle.com/technetwork/java/javamail/index-138643.html and add it to your project class path and try?

Sending Email using java timeout exception

I am trying to send email to gmail using java. I am using this code.
final String username = "xyz#gmail.com";
final String password = "**********";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port","587");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xyz#gmail.com"));
message.setRecipient(Message.RecipientType.TO,newInternetAddress("abcdef#gmail.com"));
message.setSubject("First email to using java");
message.setContent("<h:body style =background-color:white> This is a test mail sent using java" + "</body>","text/html; charset=utf-8");
Transport.send(message);
System.out.println("Message Sent");
But When i run the above code it shows follwoing error:
Exception in thread "main" com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
I have an Internet connection which uses proxy server and requires authentication. Is this error because of Proxy or there is some problem in my code. Please tell me how to resolve it.
JavaMail can't use a web proxy server directly, although it can use a SOCKS proxy server. If you only have a web proxy server, programs like Corkscrew can help.
You can setup SOCKS proxy server in JavaMail with like this:
Properties p = System.getProperties();
p.setProperty("proxySet","true");
p.setProperty("socksProxyHost","192.168.1.1");
p.setProperty("socksProxyPort","1234");
Yes, it's because of your proxy server.
How do I configure JavaMail to work through my proxy server?
the above link expired: check this link
http://www.oracle.com/technetwork/java/faq-135477.html#proxy

Categories