Javamail and Gmail Pop3 SSL - gmail

i'm trying to connect my app to Gmail to check emails. I must use SSL for POP3.
This is my code:
Properties props = new Properties();
props.put("mail.host", "pop.gmail.com");
props.put("mail.store.protocol", "pop3s");
props.put("mail.pop3s.auth", "true");
props.put("mail.pop3s.port", "993");
Session session = Session.getDefaultInstance(props, null);
Store store=session.getStore();
store.connect("myuser#gmail.com","mypass");
And I get this error:
Exception in thread "main" javax.mail.MessagingException: Connect failed;
nested exception is:
java.io.IOException: Unexpected response: * OK Gimap ready for requests from x.x.x.x.x z50if25691877wef.13
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:210)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:196)
I think this has a good new: the gmail server answered, however... seems to answer in a bad way for javamail.

The port should be 995 for gmail: http://support.google.com/mail/bin/answer.py?hl=en&answer=13287

I think it will help you
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.ssl.enable", true);
properties.put("mail.pop3.ssl.trust", "*");
properties.put("mail.pop3.port", 995);
Session emailSession = Session.getDefaultInstance(properties); `enter code here`

Related

Facing Caused by: java.net.UnknownHostException: login.microsoftonline.com

I am calling microsoft Azureurl with restTemplate in springboot application
Url:-https://login.microsoftonline.com/{{tenantId}}/oauth2/v2.0/token
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type","client_credentials");
map.add("client_id","xxxxxxxxxxxxxxxxxxxxxxxxxx");
map.add("client_secret","xxxxxxxxxxxxxxxxxx");
map.add("scope","https://graph.microsoft.com/.default");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity<String> response =
restTemplate.exchange("https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c\n/oauth2/v2.0/token",
HttpMethod.POST,
entity,
String.class);
if (response.getStatusCode() == HttpStatus.OK) {
System.out.println("Request Successful");
} else {
System.out.println("Request Failed");
}
While running the above sample call to connect with Azure, we are getting the Exception as : Caused by: java.net.UnknownHostException: login.microsoftonline.com
Later tried at home, where there is no Proxy to connect to the internet, and then am able to successfully get output without this "UnknownHostException" error.
So how to resolve the issue.
Your url seems to be not specification https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c\n/oauth2/v2.0/token, try to change it to: https://login.microsoftonline.com/xxxxxxxxxx-xxxxxx-c666dbeda42c/oauth2/v2.0/token . Remove \n.
I have the same error for a missing proxy configuration. (I was googling for solutions for a specific case)
"Host not found" has nothing to do with the url parameters, but as said just before, having "\n" in an url is never a good idea.

What's the best way to handle reconnection with MqttPahoMessageHandler as token has now expired?

I have used the following example as a basis for my own code to publish to a MQTT server: https://github.com/spring-projects/spring-integration-samples/blob/master/basic/mqtt/src/main/java/org/springframework/integration/samples/mqtt/Application.java
I have a particular use case where the password is a token in particular a keycloak token which will expire. If for whatever reason the spring application loses connection with the MQTT server and tries to reconnect the token will have expired and an MqttSecurityException: Not authorized to connect exception will be thrown. I tried extending the method connectionLost in MqttPahoMessageHandler but as the MqttPahoClientFactory & IMqttAsyncClient are private final there is not much I can do. Wondering if there is any other approach I've not thought of or is the library just not meant to be used like this???
Thanks for any replies.
We get the MqttConnectOptions from the client factory each time we try to connect so you should be able to just update the password there.
If that doesn't work for some reason, open a new feature request.
EDIT
Regarding your comment, what's wrong with this?
#Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
MqttConnectOptions options = new MqttConnectOptions();
options.setServerURIs(new String[] { "tcp://localhost:1883" });
options.setUserName("guest");
options.setPassword("guest".toCharArray());
factory.setConnectionOptions(options);
return factory;
}
#Bean
public ApplicationRunner runner(MqttPahoClientFactory mqttClientFactory, MqttPahoMessageHandler handler) {
return args -> {
Thread.sleep(30_000);
System.out.println("Changing password");
mqttClientFactory.getConnectionOptions().setPassword("foo".toCharArray());
handler.stop();
handler.start();
};
}
foo
2020-03-10 17:42:33.560 INFO 95638 --- [iSampleConsumer] siSample
: foo sent to MQTT, received from MQTT
Changing password
foo
2020-03-10 17:43:08.705 ERROR 95638 --- [ask-scheduler-3] o.s.integration.handler.LoggingHandler
: org.springframework.messaging.MessageHandlingException: error occurred in message handler [bean 'mqttOutbound' for component 'mqttOutFlow.org.springframework.integration.config.ConsumerEndpointFactoryBean#1'; defined in: 'com.example.demo.So60610337Application'; from source: 'org.springframework.core.type.StandardMethodMetadata#79da8dc5']; nested exception is org.springframework.messaging.MessagingException: Failed to connect; nested exception is Bad user name or password (4), failedMessage=GenericMessage [payload=foo sent to MQTT, headers={id=4eab5b52-726f-7ea3-252d-77c4d0401cc8, timestamp=1583876588662}]
...
Caused by: Bad user name or password (4)

JavaMail from OpenShift: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted

I have an application deployed on OpenShift, from which I need to send email to and from a single Google account.
With the application deployed locally, it works perfectly; however, when trying the same with the application deployed on OpenShift, I get the following authorisation error:
19:23:16,265 ERROR [stderr] (default task-2) javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
https://support.google.com/mail/answer/14257 wn10sm1673177wjc.46 - gsmtp
19:23:16,266 ERROR [stderr] (default task-2) at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:843)
Everything else works perfectly in my OpenShift deployment.
This is what my implementation looks like:
Properties props = new Properties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", myEmail);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(myEmail));
InternetAddress toAddress = new InternetAddress(myEmail);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(title);
message.setText(msg);
Transport transport = session.getTransport("smtp");
transport.connect(host, myEmail, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
I have tried the following solutions proposed in the URL from the exception trace and as answers to other SO questions:
Allowed less secure apps is ON in Google settings
Tried with both user#gmail.com and user for the sender
Allowed access to the Google account from https://accounts.google.com/b/0/DisplayUnlockCaptcha
The 2-step verification is OFF in Google settings
Waited >10 minutes between tries, to allow for some "cool-off" between unsuccessful authorisations

mBeans Client deployed on weblogic gives a security exception?

iam trying to follow the documentation of the mbeans for weblogic and create a web application
to access an already created custom beans running in another application deployed in the server .
iam using this code
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
String serverName = System.getProperty("weblogic.Name");
ObjectName on =new ObjectName("com.myCompanyName:Name=MyCutomBean,Type=MyCutomBean");
boolean boolresult=(Boolean)server.invoke(on, "myMethod",
new Object[]{"a","b","c"}
,new String[]{"java.lang.String","java.lang.String","java.lang.String"}); //throw exception
out.print(result);
out.print(boolresult);
when i try to access our custom beans i got this exception :
Access not allowed for subject: principals=[], on ResourceType: Name Action: execute, Target: myMethod
what could be the problem ?
i finally find a solution
to avoid this exception u need to authenticate your Context using the following :
Hashtable props = new Hashtable();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.SECURITY_PRINCIPAL, "<userName>");
props.put(Context.SECURITY_CREDENTIALS, "<password>");
Context ctx = new InitialContext(props); MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
Hope this will help someone

c# MailMessage class - How to verify server carried out the message

using (MailMessage message = new MailMessage())
{
message.From = new MailAddress(userEmail.InnerText);
message.To.Add(new MailAddress("myemail#email.com"));
message.Subject = selection.Text;
message.Body = htmlBody();
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("142.16.0.142");
client.Send(message);
}
How do I verify client.send(message) succeded?
Put Send() method inside try..catch block and catch SmtpFailedRecipientsException:
try
{
client.Send(message);
}
catch(SmtpFailedRecipientsException smtpFex)
{
string failedRecipient = smtpFex.FailedRecipient;
// it will return FailedRecipient's emailID. Now check the value of failedRecipient
//and take the action/s.
}
You can not really be sure that the message was succeeded. There is no exact way to verify that the message was delivered. Enclose the statements in a try catch block and see if it catches an exception.
" Send sends e-mail to the accepted recipients and then a SmtpFailedRecipientsException is thrown. The exception will contain a listing of the recipients that were rejected." You can refer http://msdn.microsoft.com/en-us/library/swas0fwc.aspx for more.
there is no way to test ifthe SMTP server is up and running with out sending a message.
the only thing you can to is wrap the .Send in a try/catch block to take an action in the case it fails(logging/etc)
You can use a try-catch block to catch any exceptions thrown which will include SMTP refusal messages. However, if the SMTP server accepts the mail for delivery, then the connection is closed and appears successful but there is no way to know if it was actaully delivered. In mail clients, read-receipts are the only true way to check if a mail was delivered successfully.

Resources