In fact I am trying to get emails through Gmail POP3, I enabled POP3 protocol in gmail but established a session and connection over SSL but I am an exception and unable to figure it out what is the actual matter behind.
here is the exception
Exception in thread "main" javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:382)
at javax.mail.Service.connect(Service.java:226)
at javax.mail.Service.connect(Service.java:246)
at EmailReciever.getEmail(EmailReciever.java:47)
at TestEmailReceiver.main(TestEmailReceiver.java:14)
and the I connected it as like
public void getEmail(String host, String port, final String userName, final String password)
throws MessagingException, IOException {
// sets POP3 properties
Properties properties = new Properties();
properties.put("mail.pop3.com", host);
properties.put("mail.pop3.port", port);
properties.put("mail.pop3.auth", "true");
// sets POP3S properties
properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port", "995");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
please help!
here is my debugging output...
DEBUG: setDebug: JavaMail version 1.5.0
DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]
DEBUG POP3: mail.pop3.rsetbeforequit: false
DEBUG POP3: mail.pop3.disabletop: false
DEBUG POP3: mail.pop3.forgettopheaders: false
DEBUG POP3: mail.pop3.cachewriteto: false
DEBUG POP3: mail.pop3.filecache.enable: false
DEBUG POP3: mail.pop3.keepmessagecontent: false
DEBUG POP3: mail.pop3.starttls.enable: false
DEBUG POP3: mail.pop3.starttls.required: false
Related
I am trying to check the TCP connection to a localhost TCP server (ActiveMQ broker) using following code:
string host = "localhost";
int port = 61616;
using (TcpClient tcpClient = new TcpClient())
{
try
{
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
Console.WriteLine("Connected.");
TimeSpan ts = TimeSpan.FromMilliseconds(150);
if (!t.Wait(ts))
{
Console.WriteLine("The timeout interval elapsed.");
Console.WriteLine("Could not connect to: {0}", port);// ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString());
}
else
{
Console.WriteLine("Port {0} open.", port);
}
}
catch (UnauthorizedAccessException )
{
Console.WriteLine("Caught unauthorized access exception-await behavior");
}
catch (AggregateException )
{
Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
}
I stopped the localhost server (ActiveMQ broker), and tried to run the above code. It threw System.AggregateException. When I started the server and ran the code; it connects to the server.
According to the documentation of TcpClient.Connect it says it will throw one of the following:
ArgumentNullException
ArgumentOutOfRangeException
SocketException
ObjectDisposedException
SecurityException
NotSupportedException
Why will it throw System.AggregateException?
This
Task t = Task.Run(() => {
tcpClient.Connect(host, port);
});
wraps your .Connect() call. And Task.Run() always throws AggregateException with the real exception inside it. In order to fix this either inspect the exception or even better use the asynchronous variant of .Connect():
Task t = tcpClient.ConnectAsync(host, port);
instead.
What i did finally is:
tcpClient.ReceiveTimeout = 5000;
tcpClient.SendTimeout = 5000;
tcpClient.Connect(host, port);
catch (SocketException) {
Console.WriteLine("Could not connect to: {0}", port);
Console.WriteLine("Socket exception. Check host address and port.");
}
It seems to be working.
I am trying to sent a mail through following java code.
Properties props = new Properties();
props.put("mail.host",mailProperties.get("mail.smtp"));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
final PasswordAuthentication pauth;
pauth = new PasswordAuthentication(""+mailProperties.get("mail.user"),""+mailProperties.get("mail.pwd"));
class MyAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return pauth;
}
}
Authenticator auth = new MyAuthenticator();
Session mail = Session.getInstance(props,auth);
mail.setDebug(true);
Message msg = new MimeMessage(mail);
Transport.send(msg);
But not being able to send mail,
only output I am getting is as follows :
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG: SMTPTransport trying to connect to host "mail.bizsolindia.com", port 465
While trying to check with telnet I am getting the response as shown in screen shot.
Kindly suggest any correction required from my side.
I have a .NET Core project using Serilog and JSNLog for client side logging. If I pass a JSON object from the client to the server and log it using Serilog, the logged JSON object is empty.
The very weird thing is that, if I have the debugger attached, the JSON is logged fine.
For example:
While debugging I get:
[11:00:01 FTL] this works
[11:00:02 INF] Request finished in 342.1967ms 200 text/plain
[11:00:02 FTL] "testMessage": "this is an error"
[11:00:02 INF] Request finished in 374.7837ms 200 text/plain
When Crtl+F5 I get:
[10:59:14 FTL] this works
[10:59:14 INF] Request finished in 253.3403ms 200 text/plain
[10:59:15 FTL] [[[]]]
[10:59:15 INF] Request finished in 267.2553ms 200 text/plain
I'm not sure if the problem is with Serilog or JSNLog, but any help would be appreciated.
I've made a very simple sample app to replicate this. Using the default .NET Core Webapp
Dependencies are as shown:
in Startup.cs:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Log.Logger = new LoggerConfiguration()
.WriteTo.Console().CreateLogger();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddSerilog();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseJSNLog(new LoggingAdapter(loggerFactory));
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
And in my front end:
<script src="~/lib/jsnlog.js/jsnlog.min.js"></script>
<script>
JL().fatal({ testMessage: "this is an error" });
JL().fatal("this works");
</script>
I had a similar issue. I took a look at JSNLog and what seemed to be the issue was the logging of the JSON .NET object that was being created when desearializing an object from the log message.
I did the following workaround:
I installed the Nuget package Destructurama.JsonNet (Install-Package Destructurama.JsonNet)
Then I changed the Logger configuration to include the destructuring:
Log.Logger = new LoggerConfiguration()
.Destructure.JsonNetTypes()
.WriteTo.Console()
.CreateLogger();
I then created a CustomLoggingAdapter class like this:
public class CustomLoggingAdapter: ILoggingAdapter
{
private ILoggerFactory _loggerFactory;
public CustomLoggingAdapter(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
public void Log(FinalLogData finalLogData)
{
ILogger logger = _loggerFactory.CreateLogger(finalLogData.FinalLogger);
Object message = LogMessageHelpers.DeserializeIfPossible(finalLogData.FinalMessage);
switch (finalLogData.FinalLevel)
{
case Level.TRACE: logger.LogTrace("{#logMessage}", message); break;
case Level.DEBUG: logger.LogDebug("{#logMessage}", message); break;
case Level.INFO: logger.LogInformation("{#logMessage}", message); break;
case Level.WARN: logger.LogWarning("{#logMessage}", message); break;
case Level.ERROR: logger.LogError("{#logMessage}", message); break;
case Level.FATAL: logger.LogCritical("{#logMessage}", message); break;
}
}
}
and changed the log to have the following format {#logMessage}
Note: LogMessageHelpers.DeserializeIfPossible can be found in the JSONLog GitHub repo
Then I changed the JSNLog configuration to take in my CustomLoggingAdapter like this:
app.UseJSNLog(new CustomLoggingAdapter(loggerFactory), jsnlogConfiguration);
and the log messages appeared.
Let me know if that helps
I have a Windows Phone 8 application whereby I am serializing an object to JSON and creating a HTTPWebRequest object and attempting to POST to a WCF Service. The problem which I am facing is that I get a: The remote server returned an error: NotFound.
This is the code in WP8:
var jsonData = JsonConvert.SerializeObject(ReportSightingRequest.Instance);
var uri = new Uri("URLGoesHere");
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = jsonData.Length;
webRequest.BeginGetRequestStream(ar =>
{
try
{
using (var os = webRequest.EndGetRequestStream(ar))
{
var postData = Encoding.UTF8.GetBytes(jsonData);
os.Write(postData, 0, postData.Length);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
webRequest.BeginGetResponse(
ar2 =>
{
try
{
using (var response = webRequest.EndGetResponse(ar2))
using (var reader = new StreamReader(response.GetResponseStream()))
{
var received = reader.ReadToEnd();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}, null);
}, null);
This is what gets spat out in the Output window:
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at [Namespace].<>c__DisplayClass2.<ReportSighting>b__1(IAsyncResult ar2)
The WCF service works fine as there are other devices which use it. Using fiddler to call the request works too and a console app succeeds no problem.
Can anyone see where I am going horribly wrong?
I am having trouble sending emails from a hotmail address using JavaMail. I verified that I can connect to smtp.live.com via telnet port 587. The interesting thing (to me) is if I change:
host = "smtp.gmail.com"
t.connect(host, username, password);
It connects to Gmail just fine on the default port and sends an email.
But if I change the code to:
host = "smtp.live.com"
t.connect(host,587, username, password);
It gives me the following error:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.live.com, port: 587;
nested exception is:
java.io.IOException: SSL handshake failure: Failure in SSL library, usually a protocol error
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol (external/openssl/ssl/s23_clnt.c:604 0xaf076228:0x00000000)
With session.setDebug(true) I get this info:
09-15 01:57:37.280: INFO/System.out(720): DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc.,1.4.1]
09-15 01:57:37.300: INFO/System.out(720): DEBUG SMTP: useEhlo true, useAuth true
09-15 01:57:37.310: INFO/System.out(720): DEBUG SMTP: trying to connect to host "smtp.live.com", port 587, isSSL true
09-15 01:57:37.330: INFO/SSLSocketFactory(720): Using factory org.apache.harmony.xnet.provider.jsse.OpenSSLSocketFactoryImpl#4007ed70
09-15 01:57:37.490: DEBUG/NativeCrypto(720): SSL_OP_NO_SSLv3 is set
09-15 01:57:37.538: ERROR/NativeCrypto(720): Unknown error 1 during connect
Looks like Hotmail isn't playing nice with OpenSSL. Does anyone have a solution for this?
Below is my code in...just in case it helps.
Thanks in advance,
J
String host = "smtp.live.com";
String username = foo#hotmail;
String password = "**";
Transport t = null;
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props);
session.setDebug(true);
try{
MimeMessage msg = new MimeMessage(session);
msg.setSubject("Testing SMTP-SSL");
msg.setContent("This is a test", "text/plain");
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(username, false));
t = session.getTransport("smtps");
t.connect(host,587, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
t.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I had the same problem with sending emails to Hotmail/Outlook...
I solved it by adding the socket factory port always to 578 in your properties like:
props.put("mail.smtp.socketFactory.port", "587");
and for hotmail case the port is 25.
props.put("mail.smtp.port", "25");
A bit late but maybe it helps ;)