Original Post ~
I am trying to send an email through java but I am getting an error that says it couldn't connect to host, port: smtp.gmail.com, 547; timeout -1;
I am trying to send it through gmail and I have imported two jar files, which are java mail api download – https://javaee.github.io/javamail/ java activation jar download – https://mvnrepository.com/artifact/javax.activation/activation/1.1.1
It takes forever to run and once it finally does finish it show that error.I would appreciate any help, even if it is just pointing me to a YouTube video or another post on this website. Thank you in advance.
Updated Post~
I had a comment saying to use 587 instead of 547 so I changed it but I am now getting an javax.mail.AuthenticationFailedException: Username and password not accepted error. I have googled and even looked on stack overflow and they say to change a setting in my google account but when I go to change it google is saying the setting is no longer available... it is the Less Secure app access.
I will love any thoughts or direction on how to fix this problem. I am on a Mac if anyone thinks that could be causing a problem.
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Properties;
public class Mail {
Session newSession = null;
MimeMultipart multiPart = new MimeMultipart();
MimeMessage mimeMessage = new MimeMessage(newSession);
public static void main(String[] args) throws MessagingException, IOException, AddressException {
Mail mail = new Mail();
mail.setupServerProperties();
mail.draftEmail();
mail.sendEmail();
}
private void setupServerProperties() {
Properties properties = System.getProperties();
properties.put("mail.smtp.port", "587"); //was 547 changed // to 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
newSession = Session.getDefaultInstance(properties, null);
}
private MimeMessage draftEmail() throws AddressException, MessagingException, IOException {
String[] emailRecipients = {"abcd#gmail.com", "abcde#gmail.com"}; //who it is going to
String emailSubject = "Test Mail";
String emailBody = "Test body of email";
for(int i =0; i< emailRecipients.length; i++ ){
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailRecipients[i]));
System.out.println("This is i" + i);
}
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(emailBody, "html/text");
multiPart.addBodyPart(bodyPart);
mimeMessage.setContent(multiPart);
return mimeMessage;
}
private void sendEmail() throws MessagingException{
String fromUser = "yourPersonalEmail#gmail.com"; //sender
String fromUserPassword = "yourPassword"; //Password for senders email
String emailHost = "smtp.gmail.com";
Transport transport = newSession.getTransport("smtp");
transport.connect(emailHost, fromUser, fromUserPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
System.out.println("Email Successfully sent");
}
}
I'm trying to create a secure webservice server and client using Rampart. Web service server was created successful. But when I created client side, I got NoSuchMethodError in ServiceClient.engageModule("rampart").
Here is my client side code:
public static void main(String arg[]) throws Exception
{
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("E:\\axis2-1.6.2\\repository", "E:\\axis2-1.6.2\\conf\\axis2.xml");
TestStub stub = new TestStub(ctx,"http://localhost:8080/Axis2WS/services/Test");
ServiceClient sc = stub._getServiceClient();
Options options = sc.getOptions();
options.setUserName("test");
options.setPassword("pass");
options.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
loadPolicy("policy.xml"));
sc.engageModule("rampart");
Test test = new Test();
test.setA(1);
stub.test(test);
stub.addWS();
}
private static Policy loadPolicy(String xmlPath) throws FileNotFoundException, XMLStreamException{
StAXOMBuilder builder = new StAXOMBuilder(xmlPath);
return PolicyEngine.getPolicy(builder.getDocumentElement());
}
Message Error:
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.axiom.soap.SOAPFaultClassifier.getValueAsQName()Ljavax/xml/namespace/QName;
at org.apache.rampart.util.RampartUtil.isSecurityFaultCode(RampartUtil.java:1929)
at org.apache.rampart.util.RampartUtil.isSecurityFault(RampartUtil.java:1919)
at org.apache.rampart.RampartEngine.isSecurityFault(RampartEngine.java:306)
at org.apache.rampart.RampartEngine.process(RampartEngine.java:73)
at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:92)
at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:168)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:364)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at com.ex.TestStub.test(TestStub.java:204)
at com.ex.service.testWS.main(testWS.java:39)
This is policy I used.
Thank for your help.
magento api using soap doesn't work due to missing magento-api.properties files, can someone help?
public class testConnection {
public static void main(String[] args) throws AxisFault {
String user = "rajeshvishnani";
String pass = "123456";
String host = "http://cypherincorporated.co.in/magento/index.php/api/soap?wsdl";
SoapConfig soapConfig = new SoapConfig(user, pass, host);
MagentoSoapClient magentoSoapClient = MagentoSoapClient.getInstance(soapConfig);
magentoSoapClient.setConfig(soapConfig);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: could not load [magento-api.properties] as a classloader resource
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:106)
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:123)
at com.google.code.magja.soap.MagentoSoapClient.getInstance(MagentoSoapClient.java:69)
at magentomanager.testConnection.main(testConnection.java:15)
Try changing the url to 'http://yoursite.com/api/v2_soap/index?wsdl=1'.
Please provide more details.
Not sure about java exception but you can try following link.
Link
I have a client that was generated by CXF using a local wsdl file. The client connects OK, and I get an expected 401 error from the web server.
The problem I've run into is not being able to properly configure preemptive auth in the client.
I've tried a number of things to no avail. The majority of examples on the web seem to focus on Spring, rather a plain old Java approach.
I'm including the main portion of the client. If anyone can give me an example of how this should be configured, I'd appreciate it. Note that I'm not looking for anything fancy. I just need to be able to authenticate and call the services.
public final class ServiceNowSoap_ServiceNowSoap_Client {
private static final QName SERVICE_NAME = new QName(
"http://www.service-now.com/foo",
"ServiceNow_foo");
private ServiceNowSoap_ServiceNowSoap_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = ServiceNowCmdbCiComm.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
ServiceNowFoo ss = new ServiceNowFoo(wsdlURL,
SERVICE_NAME);
ServiceNowSoap port = ss.getServiceNowSoap();
{
System.out.println("Invoking deleteRecord...");
java.lang.String _deleteRecord_sysId = "";
java.lang.String _deleteRecord__return = port
.deleteRecord(_deleteRecord_sysId);
System.out.println("deleteRecord.result=" + _deleteRecord__return);
}
System.exit(0);
}
}
Another aproach would be:
import javax.xml.ws.BindingProvider;
public class CxfClientExample {
public static void main(String[] args) throws Exception {
String endPointAddress = "http://www.service-now.com/foo";
ServiceNowFoo service = new ServiceNowFoo();
ServiceNowFooPortType port = service.getServiceNowFoo();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPointAddress);
bindingProvider.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "theusername");
bindingProvider.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "thepassword");
String deleteRecord_return = port.deleteRecord("");
System.out.println("deleteRecord.result=" + deleteRecord_return);
}
}
OK, I figured this out. Pretty straightforward when it comes down to it. Hope this saves somebody a couple of minutes...
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
private static final QName SERVICE_NAME = new QName(
"http://www.service-now.com/foo",
"ServiceNow_foo");
private ServiceNowSoap_ServiceNowSoap_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = ServiceNowFoo.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
ServiceNowFoo ss = new ServiceNowFoo(wsdlURL,
SERVICE_NAME);
ServiceNowSoap port = ss.getServiceNowSoap();
Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getAuthorization().setUserName("theusername");
http.getAuthorization().setPassword("thepassword");
// Do your work here.
}
You can also use interceptors. One benefit of using interceptor is that you can attach it to all your clients , streamlining your pre-emptive authentication approach.
Take a look at :
How do i modify HTTP headers for a JAX-WS response in CXF?
Hi Friend you have configured the authentication part after invoking the webservice, how does this works ?
Client client = ClientProxy.getClient(port);
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getAuthorization().setUserName("theusername");
http.getAuthorization().setPassword("thepassword");
I need to send simple html-message with JavaMail. And when I tried to find some nice examples with explanations in the Internet, each next example made me more angry and angry.
All those silly examples contain copied and pasted Java code which differs only in comments and a nice disclaimer that first you should config your smtp and pop3 server.
I understand that nobody wants to make an advertise for some concrete products but configuring the server is imho the hardest part. So, can anyone give me some really useful information (without java code) about configuring concrete server (Kerio, for example, or any other one)?
What I have now is the next exception:
250 2.0.0 Reset state
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Relaying to <mymail#mycompany.com> denied (authentication required)
UPD. Simple reformulation of all previous text is: imagine that you have Windows, jdk, and nothing else. And you want to make java program and run it on your machine. And this program should send "Hello world!" to your gmail account. List your steps.
UPD2. Here is the code:
Properties props = new Properties ();
props.setProperty ("mail.transport.protocol", "smtp");
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty ("mail.user", "my_real_address_1#gmail.com");
props.setProperty ("mail.password", "password_from_email_above");
Session mailSession = Session.getDefaultInstance (props, null);
mailSession.setDebug (true);
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject ("HTML mail with images");
message.setFrom (new InternetAddress ("my_real_address_1#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO,
new InternetAddress ("my_real_address_2#gmail.com"));
transport.connect ();
transport.sendMessage (message,
message.getRecipients (Message.RecipientType.TO));
And exception is:
RSET
250 2.1.5 Flushed 3sm23455365fge.10
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 3sm23455365fge.10
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1829)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1368)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:886)
at com.teamdev.imgmail.MailSender.main(MailSender.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
If you're looking for a tutorial to configure an SMTP server, you shouldn't be looking for JavaMail. Simply look for a tutorial on your server of choice (Kerio, for example ... or Exim, SendMail, Apache James, Postfix) or ask on Serverfault. Any SMTP-compliant server will play nicely with JavaMail.
Alternatively, you may even use any "standard" mail provider's infrastructure. For example, I use a Google Apps account along with Google's SMTP infrastructure to send mail from our Java applications. Using a Gmail account is a good starting point anyway if you don't want to setup your own SMTP server in order to simply testdrive JavaMail.
As a last option, you might even lookup the MX Records for a domain and deliver your mails directly to the SMTP server of the recipient. There are some common gotchas to workaround tough.
As a last point, you'll have to look into how to avoid that your mails be filtered as spam - which is a huge topic itself. Here it helps to rely on standard providers that will deal with some of the issues you might encounter when hosting your own server.
Btw: Regarding the error message you posted: the SMTP server is denying relaying of messages. This is if your SMTP server (thinks that it) is running on example.com and you're sending as bob#example.net to alice#example.org, you're asking the SMTP server to act as a relay. This was common practice several years ago, until it was - you guessed it - abused by spammers. Since those days, postmasters are encouraged to deny relaying. You have two choices: authenticate before sending mail or send to accounts hosted at your server only (i.e. on example.com, e.g. alice#example.com).
Edit:
Here is some code to get you started with authenticationg (works with Gmail accounts but should do for your own server as well)
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("john.doe#gmail.com", "mypassword");
}
});
}
I can see part of your problem. It's adequately explained in the error message.
The SMTP server you are sending your mail to (i.e. one of the addresses you've configured in your JavaMail configuration) is refusing to forward mail to mymail#company.com. Looks like a configuration issue in your SMTP server. As sfussenegger indicated, it has nothing to do with javamail.
So you're not debugging on all fronts at the same time, it might be a good idea to try addressing your SMTP server from a known working SMTP client. Thunderbird would do fine, for example. If you can send mail through it from Thunderbird, there should be little problem from JavaMail.
Update:
The correct address for Google's SMTP server is: smtp.gmail.com . Is this the server you have configured in JavaMail? Can you show us the matching error message?
A working example combining the above answers, using activation-1.1.jar and mail-1.4.1.jar and the SMTP host is Gmail.
Replace user#gmail.com and user_pw in line return new PasswordAuthentication("user#gmail.com", "user_pw");
Also, you want to replace myRecipientAddress#gmail.com by the email address where you want to receive the email.
package com.test.sendEmail;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class sendEmailTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sendEmailTest emailer = new sendEmailTest();
//the domains of these email addresses should be valid,
//or the example will fail:
emailer.sendEmail();
}
/**
* Send a single email.
*/
public void sendEmail(){
Session mailSession = createSmtpSession();
mailSession.setDebug (true);
try {
Transport transport = mailSession.getTransport ();
MimeMessage message = new MimeMessage (mailSession);
message.setSubject ("HTML mail with images");
message.setFrom (new InternetAddress ("myJavaEmailSender#gmail.com"));
message.setContent ("<h1>Hello world</h1>", "text/html");
message.addRecipient (Message.RecipientType.TO, new InternetAddress ("myRecipientAddress#gmail.com"));
transport.connect ();
transport.sendMessage (message, message.getRecipients (Message.RecipientType.TO));
}
catch (MessagingException e) {
System.err.println("Cannot Send email");
e.printStackTrace();
}
}
private Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty ("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "" + 587);
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty ("mail.transport.protocol", "smtp");
// props.setProperty("mail.debug", "true");
return Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user#gmail.com", "user_pw");
}
});
}
}
This should work:
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Emailer {
public static void main(String[] args) {
String hostname = args[0];
final String userName = args[1];
final String passWord = args[2];
String toEmail = args[3];
String fromEmail = args[4];
String subject = args[5];
String body = "";
// add rest of args as one body text for convenience
for (int i = 6; i < args.length; i++) {
body += args[i] + " ";
}
Properties props = System.getProperties();
props.put("mail.smtp.host", hostname);
Session session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, passWord);
}
});
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(fromEmail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
System.out.println("Cannot send email " + e);
}
}
}
You need to put the JavaMail mail.jar on your classpath for the javax.mail dependencies.
I'm not sure if Google lets you send email like you want to. How about trying another email provider, like your ISP's?