Asp.Net Core MVC - Mailjet is not sending emails - asp.net-core-mvc

I am using mailjet email service in my website to send emails. I have made sure that my SPF and DKIM records are up to date with my domain. However, when I run the project and register the user, it suppose to send email to the user's email id. It doesn't show any type of error but simply doesn't send the email. I have tried multiple times to change my code but still I am not able to send emails. Is there something I am missing in this context?
here is the code for the EmailSender.cs file :
using Mailjet.Client;
using Mailjet.Client.Resources;
using Microsoft.AspNetCore.Identity.UI.Services;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Derawala.Models
{
public class EmailSender : IEmailSender
{
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
return Execute(email, subject, htmlMessage);
}
public async Task Execute(string email, string subject, string body)
{
MailjetClient client = new MailjetClient("******************", "*****************");
MailjetRequest request = new MailjetRequest
{
Resource = Send.Resource,
}
.Property(Send.Messages, new JArray {
new JObject {
{
"From",
new JObject {
{"Email", "*********************"},
{"Name", "Derawala Education & Charitable Trust"}
}
}, {
"To",
new JArray {
new JObject {
{
"Email",
email
}, {
"Name",
"Derawala Trust"
}
}
}
}, {
"Subject",
subject
},
{
"HTMLPart",
body
},
}
});
await client.PostAsync(request);
}
}
}
P.S. - I have hidden public key and secret key for this question only, in program I am using the real ones.
In above image, we can see that SPF and DKIM are up to date with the domain.

Related

Calling .Net Odata API from GraphQL API Query and Mutation

my requirement is to call Odata .net API from GraphQL service.
My GQL query
query
{
cARequests {
id
cARequestStatus
reviewedBy {
name
email
}
assignedTo {
name
email
}
reviewedBy {
name
}
requestDate
reasonIfRejected
mPxN
mPxN
account {
accountNumber
}
}
}
My ODATA Request
[HttpGet(Name = "GetCARequest")]
[EnableQuery(PageSize=10)]
public IQueryable<GQLOdata> Get()
{
return Enumerable.Range(1, 5).Select(index => new GQLOdata
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.AsQueryable();
}
I dont know how to call this ODATA API from GraphQL API. What configuration I have to make and what services I have to add. Please guide me in the right direction

Publish events with MassTransit

I'm trying to publish message in one microservice and get it in another one, but cannot implement this using MassTransit 5.5.3 with RabbitMQ.
As far as I know we don't have to create a ReceiveEndpoint to be able to publish event so I'm just creating the same message interface in both services and publish a message, but as I can see in RabbitMQ it either goes to nowhere (if doesn't mapped to a queue) or goes to "_skipped" queue.
Publisher:
namespace Publisher
{
class Program
{
static async Task Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
IRabbitMqHost host = cfg.Host("host", "vhost", h =>
{
h.Username("xxx");
h.Password("yyy");
});
});
bus.Start();
await bus.Publish<Message>(new { Text = "Hello World" });
Console.ReadKey();
bus.Stop();
}
}
public interface Message
{
string Text { get; set; }
}
}
Consumer:
namespace Consumer
{
class Program
{
static async Task Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
IRabbitMqHost host = cfg.Host("host", "vhost", h =>
{
h.Username("xxx");
h.Password("yyy");
});
cfg.ReceiveEndpoint(host, e =>
{
e.Consumer<MbConsumer>();
});
});
bus.Start();
bool finish = false;
while(!finish)
{
await Task.Delay(1000);
}
bus.Stop();
}
}
public interface Message
{
string Text { get; set; }
}
public class MbConsumer : IConsumer<Message>
{
public async Task Consume(ConsumeContext<Message> context)
{
await Console.Out.WriteLineAsync(context.Message.Text);
}
}
}
I'm expeting the consumer to get the message once it's been published but it doesn't get it. I think this is because the full message types are different ("Publisher.Message" vs. "Consumer.Message") so message contract is different. How should I fix this code to get the event in the consumer? Looks like I'm missing some fundamental thing about RabbitMQ or MassTransit.
Your guess is correct. MassTransit uses the fully qualified class name as the message contract name. MassTransit also uses type-based routing, so FQCNs are used to create exchanges and bindings.
So, if you move your message class to a separate namespace like:
namespace Messages
{
public interface Message
{
string Text { get; set; }
}
}
You then can reference this type when you publish a message
await bus.Publish<Messages.Message>(new { Text = "Hello World" });
and define your consumer
public class MbConsumer : IConsumer<Messages.Message>
{
public async Task Consume(ConsumeContext<Message> context)
{
await Console.Out.WriteLineAsync(context.Message.Text);
}
}
it will work.
You might want also to look at RMQ management UI to find out about MassTransit topology. With your code, you will see two exchanges, one Publisher.Message and another one Consumer.Message where your consumer queue is bound to the Consumer.Message exchange, but you publish messages to the Publisher.Message exchange and they just vanish.
I would also suggest specifying a meaningful endpoint name for your receive endpoint:
cfg.ReceiveEndpoint(host, "MyConsumer", e =>
{
e.Consumer<MbConsumer>();
});

EasyPost Create Webhook returns null

I tried to create an easy post webhook using easy post in asp.net core API project. it returns a null value in webhook creations.
i tried this
using EasyPost;
EasyPost.ClientManager.SetCurrent("<YOUR_TEST/PRODUCTION_API_KEY>");
Webhook webhook = Webhook.Create(
new Dictionary<string, object>() {
{ "url", "https://www.foobar.com" }
}
);
I was able to have the webhook create method return JSON properly by using the most current version of the C# client library. This is the code snippet I used:
using System;
using System.Collections.Generic;
using EasyPost;
using Newtonsoft.Json;
namespace create_webhook
{
class createWebhook
{
static void Main(string[] args)
{
EasyPost.ClientManager.SetCurrent(Environment.GetEnvironmentVariable("EASYPOST_API_KEY"));
Webhook webhook = Webhook.Create(
new Dictionary<string, object>() {
{ "url", "https://www.foobar.com" }
}
);
Console.WriteLine(JsonConvert.SerializeObject(webhook, Formatting.Indented));
}
}
}
Response:
{
"id": "hook_123...",
"mode": "test",
"url": "https://www.foobar.com",
"disabled_at": null
}
For reference, the API docs related to creating a webhook for C# do not specifically mention to print what is returned which is why in my example I added a print statement.

Passing multiple parameters to web API GET method

I have created a WEB API using MySQL Database. The API works as expected for now. I sent a meter serial number and a date time parameter and then GET the expected result. Below is my controller
public MDCEntities medEntitites = new MDCEntities();
public HttpResponseMessage GetByMsn(string msn, DateTime dt)
{
try
{
var before = dt.AddMinutes(-5);
var after = dt.AddMinutes(5);
var result = medEntitites.tj_xhqd
.Where(m =>
m.zdjh == msn &&
m.sjsj >= before &&
m.sjsj <= after).Select(m => new { MSN = m.zdjh, DateTime = m.sjsj, Signal_Strength = m.xhqd }).Distinct();
return Request.CreateResponse(HttpStatusCode.Found, result);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
}
Below is my WebApiConfig file
config.Routes.MapHttpRoute(
name: "GetByMsn",
routeTemplate: "api/{controller}/{action}/{msn}/{dt}",
defaults: null,
constraints: new { msn = #"^[0-9]+$" , dt = #"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$" }
);
The URL is http://localhost:14909/api/meters/GetByMsn/002999000171/2017-10-10T10:08:20
The response I GET is
[{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:04:39",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:06:35",
"Signal_Strength": "19"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:08:31",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:10:27",
"Signal_Strength": "20"
},
{
"MSN": "002999000171",
"DateTime": "2017-10-10T10:12:23",
"Signal_Strength": "20"
}]
This all scenario works when a single serial number is passed. But at client side there would be more than one different serial numbers. For this I had to make my method to work both for one and more than one serial numbers provided the date time will be the same for all.
One solution is to create a new method a pass the multiple serial number strings, but this will not help because the number of serial numbers are dynamic i.e. they may be one, two to 100's. So setting a hard coded method won't be a solution.
I have searched for it but most of the times I have found the static method again and again. But this solution looks some what helpful but again I don't know whether it will work or not.
Any help would be highly appreciated.
You can pass a custom model to an action method, but I suggest not using the GET for you task because GET does not have a body.
Instead, use the SEARCH verb and put the list of serials number and the date inside a custom model in the body.
public class MeterSearchModel
{
public List<string> Serials {get;set;}
public DateTime Date {get;set;}
}
In .NET Core 2 your controller would have something like -
[AcceptVerbs("SEARCH")]
public async Task<IActionResult> Search([FromBody] MeterSearchModel model)
{
//..perform search
}

Email Validation in a controller Grails

I'm just trying to validate an email address in a Controller which I thought would be simple. The method I've done is as follows:
def emailValidCheck(String emailAddress) {
EmailValidator emailValidator = EmailValidator.getInstance()
if (!emailAddress.isAllWhitespace() || emailAddress!=null) {
String[] email = emailAddress.replaceAll("//s+","").split(",")
email.each {
if (emailValidator.isValid(it)) {
return true
}else {return false}
}
}
}
This is being used with a sendMail function, which my code for that is here:
def emailTheAttendees(String email) {
def user = lookupPerson()
if (!email.isEmpty()) {
def splitEmails = email.replaceAll("//s+","").split(",")
splitEmails.each {
def String currentEmail = it
sendMail {
to currentEmail
System.out.println("what's in to address:"+ currentEmail)
subject "Your Friend ${user.username} has invited you as a task attendee"
html g.render(template:"/emails/Attendees")
}
}
}
}
This works and sends emails to valid email addresses, but if I put in something random that is not an address just breaks with sendMail exception. I can't understand why it's not validating correctly and even going into the emailTheAttendees() method ... which is being called in the save method.
I would suggest using constraints and a command object to achieve this. Example:
Command Object:
#grails.validation.Validateable
class YourCommand {
String email
String otherStuffYouWantToValidate
static constraints = {
email(blank: false, email: true)
...
}
}
Call it like this in your controller:
class YourController {
def yourAction(YourCommand command) {
if (command.hasErrors()) {
// handle errors
return
}
// work with the command object data
}
}

Resources