sending email from spring app using godaddy - spring

Hi i'm trying to send mail from my spring boot app using godaddy email.
I have purchase the domain name and email id .Now i want to send mail from that domain, but it showing some errors.
public boolean sendMail(String to, String subject, String content) {
String from = "info#mydomain.com";
String password ="***********";
try {
Properties props = System.getProperties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtpout.mydomain.com");
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.auth", "true");
props.setProperty("mail.user", from);
props.setProperty("mail.password", password);
Session mailSession = Session.getDefaultInstance(props);
// mailSession.setDebug(true);
Transport transport = mailSession.getTransport("smtp");
MimeMessage message = new MimeMessage(mailSession);
message.setSentDate(new java.util.Date());
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setContent(content, "text/html");
transport.connect("smtpout.mydomain.com",from,password);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Errors:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtpout.mydomain.com, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect

Related

Jetty httpclient add proxy socks4

When i'm trying to send request via jetty httpClient with new Socks4Proxy(socksHost, socksPort); received: java.util.concurrent.ExecutionException: java.io.IOException: SOCKS4 tunnel failed with code 91
HttpClient httpClient = new HttpClient();
ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
Socks4Proxy proxy = new Socks4Proxy(socksHost, socksPort);
proxyConfig.getProxies().add(proxy);
httpClient.start();
String url = config.getProperty(stringUrl);
Request request = httpClient.newRequest(url);
request.method(HttpMethod.GET);
request.onResponseContent(new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
String s = getContentAsString();
logger.debug("Received http response message: '{}', status: '{}'", s, result.getResponse().getReason());
}
});
try {
request.send();
} catch (Exception e) {
throw new RuntimeException(e);
}
Per https://www.openssh.com/txt/socks4.protocol
Your 91 status means that request was rejected or failed. The user or source program is not authorized to access the proxy server.
Perhaps your SOCKS4 proxy has an authentication requirement.

Spring RestTemplate Connection Timeout

Any help or hint would be greatly appreciated it.
I tried the below RestTemplate code in Eclipse and Intellij and I get the same connection timeout error. If I run it on a browser I am able to connect.
enter image description here
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect
try {
String tempUrl = registryUrl;
if (roleInput.getNodeId() != null) {
tempUrl = tempUrl + roleInput.getNodeId();
}
URI uri = new URI(tempUrl);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization",auth);
headers.set("Content-Type","application/json");
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
RestTemplate restTemplate = new RestTemplate();
// ResponseEntity<String> response = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,String.class);
ResponseEntity<NodeModel> response1 = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,NodeModel.class);
NodeModel response = restTemplate.getForObject("https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s",NodeModel.class);
System.out.println("response from registry:"+response);
}
log.info("createRole,After call authLibService.validateToken(auth):"+auth);
} catch (Exception e) {
log.error("Failed to check permission, createRole getMessage error: {}", e.getMessage());
log.error("Failed to check permission, createRole getStackTrace error: {}", e.getStackTrace());
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

httpclient post basic authentication

Is there an easier way to setup the http client for preemptive basic authentication than what described.
I have to post from my spring boot service to another external service, but this is not possible in my attempt.
What a mistake I made in doing this.
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "user1Pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
HttpPost httpPost = new HttpPost("http://91.204.239.42:8083/broker-api/send");
httpPost.setHeader("Content-type", "application/json");
try {
httpPost.setEntity(new StringEntity(json));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
return statusCode;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 500;
this stacktrace
org.apache.http.conn.HttpHostConnectException: Connect to 91.204.239.42:8083 [/91.204.239.42] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:156) ~[httpclient-4.5.9.jar:4.5.9]
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374) ~[httpclient-4.5.9.jar:4.5.9]
I tried many methods but to no avail. Then I decided to contact the api manufacturer and they would tell me that this api only works if we allow it. He started working when he got permission. The cause of the problem is permissions

email not send in spring

I want to send an email with spring boot that's way I'm setting this configuration in my aplication.properties :
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.host=xxxxx.hostgator.com
spring.mail.port=465
spring.mail.username=XXX#xxxx.com
spring.mail.password=XXXX
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
but the problem is when i test it with postman the request is always in the state "loading" :
when i test the function with an gmail account it works fin!
my fucntion :
public void sendPaimentEmail(String to, String subject, String text) {
MimeMessage message = emailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
FileSystemResource imageSignature = new FileSystemResource(new File(this.pathToSaveFile2 + "logo.png"));
if (null != imageSignature && imageSignature.exists()) {
helper.addInline("logo", imageSignature);
}
FileSystemResource file = new FileSystemResource(new File(this.pathToSaveFile2 + "historique.png"));
helper.addAttachment("Invoice", file);
this.emailSender.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}

Redirect to another URL and back for Certifcate base Login

Currently i developing an application which have two routes which are in different domain.
Example :
Route 1: https://test.apps.com
Route 2: https://test.cert-apps.com
Users uses Route 1 to access the application. In the Login page there is an option for Certificate based login . But certificate based authentication is only enabled in route 2.
So how do i do the certificate based authentication by redirecting from Route 1 to Route 2 and once client is authenticated redirect to route 1.
Following are the code that i currently using which are not working:
#Controller
#RequestMapping("/login")
public class LoginContr {
#RequestMapping("/certificate")
public String message(HttpServletRequest request, HttpServletResponse response) {
try {
sendGET();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "login";
}
#RequestMapping("/extractcertificate")
private String extractEmailFromCertificate(HttpServletRequest request) {
String email = "";
//Code to extract email from certificate
return email;
}
private static void sendGET() throws IOException {
URL obj = new URL("https://test.cert-apps.com/login/extractcertificate");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
}
}
The above code gives the error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
sendGet() method sends a request to Route 2 and calls /extractcertificate webservice to do certificate based authentication and once its done it will retrive the email address.
Technology using for app: Java,Spring,Angualar 4, Cloud Foundary
Is there any alternative to do this or any inbuilt implementation , any tips would be great advantage..

Resources