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.
Related
Recently, I just started to learn on SignalR and I had been testing on one project that I found on GitHub. However I did stuck when trying to Post data to Web api part.
I just get everything done yet I cannot really make this project to work somehow. This is basically the program for the project. It is a console app and did send the data(Json) to Web Api
// Get the stuff we need to send
GetMetrics(out cpuTime, out memUsage, out totalMemory);
// Send the data
var postData = new
{
MachineName = System.Environment.MachineName,
Processor = cpuTime,
MemUsage = memUsage,
TotalMemory = totalMemory
};
var json = JsonConvert.SerializeObject(postData);
// Post the data to the server http://localhost:80/api/cpuinfo
var serverUrl = new Uri(ConfigurationManager.AppSettings["ServerUrl"]);
var client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.UploadString(serverUrl, json);
Moving to web part. I did have the Asp.net MVC and did create the RouteConfig inside the App_Start to route HTTP request to controller.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And this is the controller class.
public class CpuInfoController : ApiController
{
public void Post(CpuInfoPostData cpuInfo)
{
var context = GlobalHost.ConnectionManager.GetHubContext<CpuInfo>();
context.Clients.All.cpuInfoMessage(cpuInfo.MachineName, cpuInfo.Processor, cpuInfo.MemUsage, cpuInfo.TotalMemory);
}
}
I also had it registered inside Global.asax as below
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
After done all this, I still cant get this done and my console application pop up some errors as in the image here. It seems like the api/cpuinfo was not found.
Please advice me if anything that I had done wrong here.
The full version of this project can be found here.
You have to modify the File App.config in "CpuInfoClient" project. (the value of the Key)
Use "http" instead of "https"
Change the port number to the actual port number (instead of 44300), that uses the web application after starting. The exact port for the substitution you can see , when the web app starts in IE or Firefox. The port is also in "WcfCpuApp -> Properties -> Web -> Project-URL
Be sure that your web application is running, when you start "CpuInfoClient"
I have a web app with cookie and JWT authentication. The site uses cookie schema, web api - JWT schema. And there is a controller, which requires both types(if request has 'Bearer' header - JWT, otherwise - cookie, but only the cookie one works. Here are ConfigureServices and Configure methods:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOptions();
services.AddCommonLogger();
services.AddAutoMapper();
services.AddDatabase(Configuration);
services.AddLogicUnits();
services.AddFrontendLogic(Configuration);
services.ConfigureSettings(Configuration);
services.AddCommonServices();
var authTokenSettings = Configuration.GetSection(nameof(TokenProviderSettings)).Get<TokenProviderSettings>();
services.AddAuthentication()
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, u =>
{
u.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = authTokenSettings.Issuer,
ValidAudience = authTokenSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authTokenSettings.Key))
};
})
.AddCookie("CookieAuthScheme", cfg => cfg.SlidingExpiration = true);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UnhandledExceptionLoggerProvider provider)
{
loggerFactory.AddNLog();
loggerFactory.AddProvider(provider);
app.AddNLogWeb();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
If I set AuthenticationScremes like this
[Authorize(AuthenticationSchemes = "Bearer,CookieAuthScheme")]
public async Task<IActionResult> MyRecords()
{ // Do some work...}
I get http 404, and if I use empty [Authorise] attribute a cookie authentication is used.
If I remove .AddCookie("CookieAuthScheme", cfg => cfg.SlidingExpiration = true); the JWT-based authentication is used and works fine. What am I doing wrong?
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
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
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 ;)