I have a Java EE web application which run on GlassFish server. I have written the following code to send emails through the application.
When I test the application in my home PC and Laptop, it send emails immediately. When I run the very same application in a google cloud server, it gives a time out exception. What can be the possible causes?
package com.divudi.ejb;
import java.util.Properties;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
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;
#Stateless
public class EmailManagerEjb {
final static String USERNAME = "mygmailaccount#gmail.com";
final static String PASSWORD = "mygmailpassword";
static Session session = null;
public void sendEmail1(String toEmail, String messageHeading, String messageBody) {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
if (session == null) {
session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USERNAME, PASSWORD);
}
});
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(USERNAME));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
message.setSubject(messageHeading);
message.setText(messageBody);
Transport.send(message);
System.out.println("Send Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
After going through the comment of stdunbar, I created firewall Exceptions for the ports 25, 465 and 587 for google cloud compute engine.
Then everything started working fine.
Now emails are been sent successfully.
If you are using App Engine, you can use JavaMail which uses the Mail API. Alternatively, if you are using Compute Engine, then we recommend that you use another mail service like Mailgun or Sendgrid.
Related
I am using Tomcat7, Sprng framework for restfull web services. I am trying to call an http web service that have basic authentication using Spring RestTemplate.
I couldn't get it to work. Can anybody please tell me based on the code below what do I need to change to make it able to call the http restfull web service that have basic authentication.. Also can anybody tell me or provide me with the pom.xml file which java libraries would I need?
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.journaldev.spring.controller.EmpRestURIConstants;
import com.journaldev.spring.model.CostControlPost;
import com.journaldev.spring.model.Employee;
import com.journaldev.spring.model.RfxForUpdate;
import static org.junit.Assert.*;
import org.apache.commons.codec.binary.Base64;
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class TestExample2 {
public static final String SERVER_LIST="http://abc/sourcing/testServices";
#Test
public void testGetListOfServiceNames()
{
try
{
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(SERVER_LIST,HttpMethod.GET,null,String.class);
assertNotNull(response);
}
catch(Exception e)
{
System.out.println("e:"+e.getMessage());
}
}
}
In simplest form:
DefaultHttpClient httpClient = new DefaultHttpClient();
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password);
httpClient.setCredentialsProvider(credentialsProvider);
ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);
template = new RestTemplate(rf);
Spring Automatic Management:
Create HTTP context for RestTemplate:
private HttpContext createHttpContext() {
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(host, basicAuth);
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
return localcontext;
}
Add the interceptors:
restTemplate.getInterceptors().add(
new BasicAuthorizationInterceptor("username", "password"));
Call:
restTemplate.exchange(
"http://abc/sourcing/testServices",
HttpMethod.GET, null, String.class);
Refer this post.
I am using the below snippet for sending emailable-report.html of testng through mail.
public class SampleSendMail {
public void sendmailfun() {
String username = "mailid";
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");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sendingmailid"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receivingmailid"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "/Users/Documents/workspace/sampleproject/test-output/emailable-report.html";
String fileName = "emailable-report.html";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
In #AfterSuite ,i'm callig this function.
public void appstop() throws IOException {
sendingemail.sendmailfun();
}
I'm getting the the following error.
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first
Can anyone help me to rectify this?
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.testng.annotations.Test;
public class SendAttachment{
#Test
public static void sendmail() throws AddressException, MessagingException, InterruptedException{
Thread.sleep(50000);
System.out.println("Test mail");
String[] to={"mail address","mail address"};
String to2="mail address";//change accordingly
final String user="mail address";//change accordingly
final String password="password";//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587"); //TLS Port
properties.put("mail.smtp.auth", "true"); //enable authentication
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
//2) compose message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mailid1,mailid2"));
message.setSubject("ECM Regression Test suite Results");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Please find the Regression Result in the attachment");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart(); MimeBodyPart messageBodyPart3 = new MimeBodyPart(); MimeBodyPart messageBodyPart4 = new MimeBodyPart(); MimeBodyPart messageBodyPart5 = new MimeBodyPart();
File f3=new File("D:\\svn\\CI_1.0\\seleniumScriptsRegression\\seleniumScriptsRegression\\test-output\\emailable-report.html");
DataSource source4 = new FileDataSource(f3);
messageBodyPart5.setDataHandler(new DataHandler(source4));
messageBodyPart5.setFileName(f3.getName());
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart5);
//6) set the multiplart object to the message object
message.setContent(multipart);
//7) send message
Transport.send(message);
System.out.println("message sent....");
}
//}
}
Try to use like this its working for me. But When we run this old email able report only getting attached in the mail.
**You can send the mail through **Apache commons Email**
=======================================================
**but before using Apache commons you need to add the dependency in Maven POM File.**
Dependency is as mentioned below
--------------------------------
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
You can refer to the below link for compatible dependency.
**Link:** https://mvnrepository.com/artifact/org.apache.commons/commons-email
**JAVA CODE**
------------
public void sendMail() throws MessagingException, EmailException
{
String username="abc.#gmail.com";
String password="1234567890";
String from_Email="xyz.#gmail.com";
String to_Email="pqr.#gmail.com";
Email email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setSSLOnConnect(true);
email.setFrom(from_Email);
email.setSubject("This is a test mail ... :-)");
email.setMsg("Body Message");
email.addTo(to_Email);
email.send();
}
I am trying to do a request to coap server (er-rest-example) using Californium.
I succesfully do a POST request.
But with PUT I am getting a BAD REQUEST, I try using this URLs in url:
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds?
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds?color=r
But with no one get success.
What I am doing wrong?.
This is my simple script:
package coap_client;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
public class cliente {
public static void main(String[] args) throws Exception {
Timer timer;
timer = new Timer();
TimerTask task = new TimerTask(){
#Override
public void run(){
String url="coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds";
URI uri= null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
CoapClient client = new CoapClient(uri);
CoapResponse response = client.put("color=r",MediaTypeRegistry.TEXT_PLAIN);
System.out.println(response.isSuccess());
if (response!=null) {
byte[] myreponse=response.getPayload();
String respuesta2 = new String(myreponse);
System.out.println(respuesta2);
}
}
};
timer.schedule(task, 10,10*1000);
}
}
In Contiki er-rest-example, see the POST/PUT handler(1) for the LED CoAP resource. It expects a mode param without which you will get a BAD_REQUEST as response. I assume that has to go in the request body.
I'm having trouble with my restful web service using embedded jetty and jersey. I'm starting the jetty server from inside of an ecplise application and I try to communicate with the server using a jersey client.
I built the restful web service based on this tutorial: http://jlunaquiroga.blogspot.se/2014/01/restful-web-services-with-jetty-and.html
I had some problems migrating the tutorial from Jersey 1.x to 2.x but finally I got the web server up and running. Now, the problem is that it does not respond to requests from client (or browser). Does anyone know why?
Here is my code:
Provider package:
package org.eclipse.eatop.jetty.helloworld.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/xmlServices")
public class XMLProjectService {
#GET
#Produces(MediaType.TEXT_XML)
public String getProject()
{
return "<?xml version=\"1.0\"?>" + "<hello> hello world </hello>" ;
}
}
Jetty embedded server:
public Object execute(ExecutionEvent event) throws ExecutionException {
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
ServletHolder sh = new ServletHolder(new ServletContainer());
sh.setInitOrder(1);
sh.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "org.eclipse.eatop.jetty.helloworld.rest");
context.addServlet(sh, "/*");
try {
server.start();
} catch (Exception e) {
System.out.println("Unable to start jetty web server");
e.printStackTrace();
}
return null;
}
Client:
public class Test {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(getBaseURI()).path("xmlServices");
System.out.println(target.request("text/xml").get());
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/").build();
}
}
The result I get :
InboundJaxrsResponse{ClientResponse{method=GET, uri="http://localhost:8080/xmlServices", status=404, reason=Not Found}}
Try this change ...
From:
ServletHolder sh = new ServletHolder(new ServletContainer());
To:
ServletHolder sh = new ServletHolder(ServletContainer.class);
That's the way that your linked to article uses it.
I too struggled on this part for two days and found that the rootcause lies in lazyinitialization of ServletContextHandler. Start your contexthandler once you start your jetty server. It will work fine.
I am creating an application where I want to send an email to my clients.When i compiled the below code its ok but when i run it gives me error as follows
java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
String to = "prakash_d22#rediffmail.com";
String from = "web#gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("smtp.gmail.com", 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();
}
}
}
error:
Please guide me.
String host = "smtp.gmail.com";
Properties properties = new Properties();
set following properties
properties .put("mail.smtp.starttls.enable", "true");
properties .put("mail.smtp.host", host);
properties .put("mail.smtp.user", username);
properties .put("mail.smtp.password", password);
properties .put("mail.smtp.port", "587");
properties .put("mail.smtp.auth", "true");
Have you read the Fundamentals of the JavaMail API?
Anyways, from what I can tell the issue is that you're using invalid configuration.
properties.setProperty("smtp.gmail.com", host);
As you can see in the JavaMail API documentation, JavaMail does not support a property named smtp.gmail.com. What you probably intended was actually...
properties.setProperty("mail.smtps.host", host);
I suspect you wish to use Gmail's SMTPS server, not one hosted on localhost as you have it now, so I'd advise changing your code such that...
final String host = "smtp.gmail.com";
You also wish to use authnetication, which JavaMail suggests you can do in their FAQ on Gmail as follows:
properties.setProperty("mail.smtps.auth", "true");
Note that Gmail requires authenticating to send mail as such. It appears another answer suggested you can configure the username/password using the session properties; unfortunately, this is incorrect.
What you want to do is use an Authenticator.
final Session session = Session.getInstance(properties, new Authenticator() {
static final PasswordAuthentication AUTH = new PasswordAuthentication(USER, PASS);
protected PasswordAuthentication getPasswordAuthentication() {
return AUTH;
}
});