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?
Related
I am stuck behind a corporate firewall that won't let me send email via conventional means such as Java Mail API or Apache Commons Email, even to other people inside the organization(which is all I want anyways). But my Outlook 2010 obviously can send these emails. I was wondering if there is a way to automate Outlook 2010 via Java code so that Outlook can send the emails ? I know stuff like "mailto" can be used pop-up the default Outlook send dialog with pre-populated info, but I am looking for a way to have the send operation happen behind the scenes. Thanks for any info.
You can send emails through outlook with javamail use the configurations described on Outlook's official site.
Here is small demo code
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public static void main(String[] args) {
final String username = "your email"; // like yourname#outlook.com
final String password = "*********"; // password here
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp-mail.outlook.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver mail")); // like inzi769#gmail.com
message.setSubject("Test");
message.setText("HI you have done sending mail with outlook");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
.
Note: I tested this with Javamail API 1.5.6
I don't think there's any way to do what you want using Outlook.
Presumably your mail server is also behind the corporate firewall. If you're using Outlook for your client, you're probably using Exchange for your server. Exchange can be configured to support the standard SMTP protocol for sending mail, which would allow use of JavaMail. If you can't configure your Exchange server to support SMTP, you still might be able to use Exchange Web Services. If that doesn't work, you might need to use one of the JavaMail Third Party Products that supports the Microsoft proprietary mail protocol.
Process p = Runtime.getRuntime().exec("cmd /C start outlook ");
i have a class that is called "NotifiationService":
#Service("notificacionService")
public class NotificacionServiceImpl implements NotificacionService{
//servicio llama a repositorio
#Autowired
#Qualifier("notificacionService")
private NotificacionService notificacionService;
#Override
public void send(String to, String subject, String text) {
//proxy
Properties p = System.getProperties();
p.setProperty("proxySet","true");
p.setProperty("socksProxyHost","MYPROXY");
p.setProperty("socksProxyPort","MYPORT");
Properties props = new Properties();
// smtp.gmail.com
props.setProperty("mail.smtp.host", "smtp.gmail.com");
// TLS
props.setProperty("mail.smtp.starttls.enable", "false");
// port
props.setProperty("mail.smtp.port","465");
//
props.setProperty("mail.smtp.user", "reciever#gmail.com");
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress("sender#gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(text);
//
Transport t = session.getTransport("smtp");
t.connect("sender#gmail.com","senderpassword");
t.sendMessage(message,message.getAllRecipients());
t.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
As you can see i have tried to configure a proxy, since the computer is connected to one that redirects the traffic. So even adding all the specifications about the proxy, it keeps giving me an error saying:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.SocketException: Permission denied: connect
I have also tried different ports like: 25,485,587 and none of the respond, so i think its a problem with the proxy.
To be able to find the information about the proxy that is implemented i have typed this command in the console:
reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" | find /i "proxyserver"
and it responds with:
ProxyServer REG_SZ MYPROXY:MYPORT
If i type: "ping google.com" in cmd, it says its inaccessible
Is there a way to be able to connect from java with javamail to gmail and be able to send an email with the current configuration?
Thanks.
If it's not working after setting the SOCKS properties, most likely your proxy server is just a web proxy server and not a SOCKS proxy server. The JavaMail FAQ has pointers to other software that will allow to tunnel connections through a web proxy server.
Since JavaMail 1.6.2, You can set proxy authentication properties for Session object for sending emails.
Refer to the following documentation link.
https://javaee.github.io/javamail/docs/api/
The following properties are introduced newly and works fine with Proxy Authentication (Basic).
mail.smtp.proxy.host
mail.smtp.proxy.port
mail.smtp.proxy.user
mail.smtp.proxy.password
To clarify at least one point concerning the usage of https.proxySet=true and http.proxySet=true.
JDK-4632974 proxySet=false is ignored for HttpURLConnection.getOutputStream
"The use of property http.proxySet was eliminated in favor of simply testing
for the presence of the http.proxyHost property. This property existed up to
JDK1.0.2 but was removed for JDK1.1 in 1996."
In other words, do not use proxySet as it serves no purpose. It is non-existing Java system property nowadays.
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
Im tring to send a simple email with this code using google app engine.
But nothing happens, is there something i have to configure in order to use the mail api?
This runs on localhost.
I am using gmail as mail host.
String host = "smtp.google.com";
String to = "example#yahoo.fr";
String from = "example#gmail.com";
String subject = "this is a test";
String messageText = "test";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
// Set debug on the Session
// Passing false will not echo debug info, and passing True will.
mailSession.setDebug(sessionDebug);
// Instantiate a new MimeMessage and fill it with the
// required information.
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);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
When running the AppEngine development server locally, anything sent via the Mail service will not actually be sent - it will just be logged to the console
See here
When an application running in the development server calls the Mail service to send an email message, the message is printed to the log. The Java development server does not send the email message.
In addition, the from address must be (from here)
The email of an app administrator
The email of the currently logged in user who signed in using a Google Account
A valid email receiving address from the app
The sender should be your own Gmail email address instead of example#gmail.com
Reason is because the SMTP server needs to authenticate you.
Apparently, GAE doesn't allow the use of the admin accounts any more. you need to use the service account: project-id#appspot.gserviceaccount.com
My previous projects still work with admin accounts, but the recently created projects just don't allow me to use any of the admin accounts.
Other than email not working on localhost or due to the sender email not being the authenticated one, I have experienced that email does not work even when the version is not the default one. I could not find this documented anywhere.
For example:
nondefaultversion-dot-myapp.appspot.com (email does not work, no error logs)
myapp.appspot.com (email works)
Please confirm if others have also faced this issue.
I set the mail.transport property to smtps, beside the very basic information for connecting to a smtps server:
Properties p = new Properties();
p.put("mail.transport.protocol", "smtps");
p.put("mail.smtps.host", "smtp.gmail.com");
p.put("mail.smtps.auth", true);
Session s = Session.getDefaultInstance(p,new Authenticator(){/*authenticator impl.*/});
MimeMessage mm = new MimeMessage(s); /*then i set the subject, then the body... */
mm.setRecipients(RecipientType.TO, "myfakeaddress#gmail.com");
And now, i try to send my message. I want to try the static method; using the instance method sendMessage it works fine. Here it is:
Transport.send(mm);
It tries to connect to a smtp server, instead of a smtps server. Stepping inside the implementation of javamail (btw, my version is 1.4.5) i've discovered that the method that fails is:
transport = s.getTransport(addresses[0]);
because it returns an SMTPTransport instead of SMTPSSLTransport; this even if i've set the mail.transport.protocol property to smtps as you can see in the second line of code.
Is my procedure buggy anywhere or it isn't possible to send smtps mails via Transport.send static method?
Transport.send(msg) is looking up the protocol(s) associated with the recipients of your email, for each type of recipient.
All your recipients are InternetAddresses, which have the type rfc822
Here are three ways to set JavaMail to use smtps protocol for rfc822 addresses:
Add the line rfc822=smtps in the property files javamail.address.map or javamail.default.address.map (as described in the Session javadoc)
Call s.setProtocolForAddress("rfc822", "smtps")` on your instantiated session (requires JavaMail 1.4 or later)
Set the property mail.transport.protocol.rfc822 to smtps when instantiating your session (requires JavaMail 1.4.3 or later)
Bill Shannon (current maintainer of Javamail) suggests in this question
Get rid of all the socket factory properties; if you're using a
reasonably recent version of JavaMail you don't need them. See the
JavaMail FAQ for how to configure JavaMail to access Gmail. You'll
also find debugging tips there if it still doesn't work.
Also, change Session.getDefaultInstance to Session.getInstance.
Here is the relevant code from the Javamail FAQ
String host = "smtp.gmail.com";
String username = "user";
String password = "passwd";
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
props.put("mail.debug", "true");
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}