Coder Social home page Coder Social logo

mandrill.net's Introduction

Mandrill.net

Simple, cross-platform Mandrill api wrapper for .NET Core

Coverage Status

API Docs

https://mandrillapp.com/api/docs/

Getting Started

dotnet add package Mandrill.net

# use Mandrill with HttpClientFactory
dotnet add package Mandrill.net.Extensions.DependencyInjection

Send a new transactional message through Mandrill

var api = new MandrillApi("YOUR_API_KEY_GOES_HERE");
var message = new MandrillMessage("[email protected]", "[email protected]",
                "hello mandrill!", "...how are you?");
var result = await api.Messages.SendAsync(message);

Send a new transactional message through Mandrill using a template

var api = new MandrillApi("YOUR_API_KEY_GOES_HERE");
var message = new MandrillMessage();
message.FromEmail = "[email protected]";
message.AddTo("[email protected]");
message.ReplyTo = "[email protected]";
//supports merge var content as string
message.AddGlobalMergeVars("invoice_date", DateTime.Now.ToShortDateString());
//or as objects (handlebar templates only)
message.AddRcptMergeVars("[email protected]", "invoice_details", new[]
{
    new Dictionary<string, object>
    {
        {"sku", "apples"},
        {"qty", 4},
        {"price", "0.40"}
    },
    new Dictionary<string, object>
    {
        {"sku", "oranges"},
        {"qty", 6},
        {"price", "0.30"}

    }
});

var result = await api.Messages.SendTemplateAsync(message, "customer-invoice");

Service Registration

It is recommended that you do not create an instance of the MandrillApi for every request, to effectively pool connections to mandrill, and prevent socket exhaustion in your app. If you are using .net dependency injection, you can use the Mandrill.net.Extensions.DependencyInjection package which includes a IServiceCollection.AddMandrill() extension method, allowing you to register all the needed interfaces and also customize the HttpClientFactory to efficiently manage the HttpClient connections.

using Microsoft.Extensions.DependencyInjection;
using Mandrill;
using Mandrill.Model;
using Mandrill.Extensions.DependencyInjection;

var services = ConfigureServices(new ServiceCollection()).BuildServiceProvider();
var api = services.GetRequiredService<IMandrillApi>();
// we can also target specific mandrill api endpoint interfaces...
//var messagesApi = services.GetRequiredService<IMandrillMessagesApi>();
var message = new MandrillMessage("[email protected]", "[email protected]",
        "hello mandrill!", "...how are you?");
var result = await api.Messages.SendAsync(message);

static IServiceCollection ConfigureServices(IServiceCollection services)
{
    services.AddMandrill(options =>
    {
        options.ApiKey = "YOUR_API_KEY_GOES_HERE"; // Load the api key from configuration
    });

    return services;
}

Processing a web hook batch

[HttpPost]
[Route("/api/some/route/outbound")]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> Outbound([FromForm(Name = "mandrill_events")] string body)
{
    if (!Request.Headers.TryGetValue("X-Mandrill-Signature", out var signature))
    {
        return Unauthorized();
    }


    var events = MandrillMessageEvent.ParseMandrillEvents(body);

    // accept an empty test request
    if (events.Count == 0)
    {
        return Accepted();
    }

    if (!ValidateRequest(body, signature, "WEBHOOK_SECRET_KEY_HERE"))
    {
        return Forbid();
    }

    foreach (var messageEvent in events)
    {
        // do something with the event
    }
    return Ok();
}


private bool ValidateRequest(string body, string signature, string authKey)
{
    var form = new NameValueCollection();
    form.Set("mandrill_events", body);
    return WebHookSignatureHelper.VerifyWebHookSignature(signature, authKey, new Uri(Request.GetDisplayUrl()), form);
}

Building

dotnet build

Testing

You must set the user environment variable MANDRILL_API_KEY in order to run these tests. Go to https://mandrillapp.com/ to obtain an api key.

In order for the email from address to match your allowed sending domains, you can set MANDRILL_SENDING_DOMAIN to match your account.

# include MANDRILL_API_KEY and MANDRILL_SENDING_DOMAIN in your env. For example:
# MANDRILL_API_KEY=xxxxxxxxx MANDRILL_SENDING_DOMAIN=acme.com dotnet test tests
dotnet test

API coverage

See this issue to track progress of api implementation

mandrill.net's People

Contributors

chriseby avatar danielmarbach avatar dependabot-preview[bot] avatar dependabot[bot] avatar ericthornton avatar feinoujc avatar kasperk81 avatar kgbhun avatar lwdeveloper avatar pieter61 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mandrill.net's Issues

MandrillInboundMessageInfo doesnt deserialize

Attachments and Images are sent as dictionarys.

Should be

public Dictionary<string,MandrillInboundAttachment> Attachments { get; set; } = new Dictionary<string,MandrillInboundAttachment>();
public Dictionary<string, MandrillInboundImage> Images { get; set; } = new Dictionary<string, MandrillInboundImage>();

How to schedule a template?

Is there a way i can schedule a template email using mandrill.net ?

var client = new MandrillApi("key");

var message = new MandrillMessage();
message.AddTo("[email protected]");
message.FromEmail = "[email protected]";
Messages.SendTemplate(message, "test")

message.AddGlobalMergeVars("key", "something-here");
client.Messages.SendTemplate(message, "template-slug");

Right now I'm using above to send the email, is there a way i can schedule it some time later. For .eg

client.Messages.ScheduleTemplate(message, "template-slug", DateTime.now.addDays(2));

Netcore support

Are you going to support .Net Core (AspNe Core) in MandrillNet?

Calling a function once a scheduled email has finally been sent

Can you provide an example of how you would go about handling the following scenario? Right now I can schedule an email and it seems to send according to that schedule fine. Every time an email is sent or scheduled, it is logged in my database. I need a call back that will allow me to change the status of a scheduled email once it has been sent. Is this possible with this wrapper?

I understand I can do this with a webhook but I just need an example of setting one up and then using it on call back if you have an example. Thanks.

Full mandrill api support

Users Calls

  • Info
  • Ping2
  • Senders

Messages Calls

  • Send
  • Send-Template
  • Search
  • Search-Time-Series
  • Info
  • Content
  • Parse
  • Send-Raw
  • List-Scheduled
  • Cancel-Scheduled
  • Reschedule

Tags Calls

  • List
  • Delete
  • Info
  • Time-Series
  • All-Time-Series

Rejects Calls

  • Add
  • List
  • Delete

Whitelists Calls

  • Add
  • List
  • Delete

Senders Calls

  • List
  • Domains
  • Add-Domain
  • Check-Domain
  • Verify-Domain
  • Info
  • Time-Series

Urls Calls

  • List
  • Search
  • Time-Series
  • Tracking-Domains
  • Add-Tracking-Domain
  • Check-Tracking-Domain

Templates Calls

  • Add
  • Info
  • Update
  • Publish
  • Delete
  • List
  • Time-Series
  • Render

Webhooks Calls

  • List
  • Add
  • Info
  • Update
  • Delete

Subaccounts Calls

  • List
  • Add
  • Info
  • Update
  • Delete
  • Pause
  • Resume

Inbound Calls

  • Domains
  • Add-Domain
  • Check-Domain
  • Delete-Domain
  • Routes
  • Add-Route
  • Update-Route
  • Delete-Route
  • Send-Raw

Exports Calls

  • Info
  • List
  • Rejects
  • Whitelist
  • Activity

Ips Calls

  • List
  • Info
  • Provision
  • Start-Warmup
  • Cancel-Warmup
  • Set-Pool
  • Delete
  • List-Pools
  • Pool-Info
  • Create-Pool
  • Delete-Pool
  • Check-Custom-Dns
  • Set-Custom-Dns

Metadata Calls

  • List
  • Add
  • Update
  • Delete

Very cool

Not an issue. Nice, it is a very nice project, really like the examples you've especially got the full sweep on web hook testing. Nice!

duplicate mails

I have used that library for sending abandoned cart mails but there is a problem that mandrill sends mail as many as number of the item in basket.

mergeLanguage = handlebars

is there anyone who can help me ?

ignore SSL

Hi, we have a mitm ssl which renders it unusable, is there a way to ignore bad certs with this library ?

Handlebars not working

Im using the following test:

message.AddGlobalMergeVars("profile", new { firstname = "Test" });
_mandrillApi.SendTemplateAsync(message, "template-name");

but the outbound email in mandrill is not being replaced, showing the below:
Firstname: {{profile.firstname}},

JsonSerializer.NullValueHandling should be Include

Mandrill.net configures JSON.NET to use NullValueHandling.Ignore, but this causes problems with loops due to the crazy nature of how loop scoping works in Mandrill's handlebars implementation (the specifics of which are covered here and here, the latter of which is from 2016 and shows that the problem is unlikely to be solved by Mandrill any time soon).

I propose changing NullValueHandling to Include since it solves this scenario... for non-array properties.

(Mandrill's array property handling appears to be even worse, requiring a non-empty array to replace the previous iteration's value. The above change will obviously not help with that)

Not working in .net core console app

This is not working in .net core 2.1.1 console app. How can we at least find the error. No emails are going and no error message. How can we send Message/Email to work in scratch .net core 2.1.1 console app?

I there any demo app which uses Mandrill.net?

Search function not filter by date

Hi,
thank you in adavance for you time.
I am using your library and I am using the Search methods to get all email in range of date from Mandrill. But, I have noticed that the filter by date does not work.

May you give a check, please?

Regards,
Achille

Add multiple BCC Adresses

Hi,

Is it possible to use your wrapper in orderto send email with multiple BCC adresses?
As I know, message.BccAddress is only for one address...

Please tell me, if I mistake

Regards

Eric

System.ArgumentNullException on Async Post

After upgrading to 7.3 started getting this exception when attempting to send an email to mandrill via SentTemplateAsync method.

Call to Mandrill failed: "System.ArgumentNullException: Value cannot be null. Parameter name: o at Newtonsoft.Json.Linq.JToken.FromObjectInternal(Object o, JsonSerializer jsonSerializer) at Mandrill.Serialization.MandrillMergeVarConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) at Mandrill.MandrillRequest.GetStreamContent[T](T value, StreamWriter writer) at Mandrill.MandrillRequest.PostAsJsonAsync[T](String requestUri, T value, CancellationToken c) at Mandrill.MandrillRequest.PostAsync[TRequest,TResponse](String requestUri, TRequest value) at Core.Providers.Mandrill.MandrillProvider.SendEmailToProviderUsingMandrill(EmailRequestMessage message, CancellationToken token, Func4 providerResponseHandler)"
`

When I downgrade to 7.2 this issue goes away.

SendTemplateAsync returns 406 Status Code

Runtime: netcoreapp3.1
Package version: 7.2.0

Response from API seems to indicate that the request body is not in the correct format. However I'm not sure how this can happen as I assume that the Mandrill.net wrapper would handle this. The exception doesn't really give much away either, just specifies a generic http 406 error.

Do you have any suggestions as to why this would happen? Also, should the wrapper throw to prevent sending requests that would result in http 406?

Can no longer build

I was going to help knock out some of the remaining API calls, did a sync with your master, and now I get loads and loads of errors on build. I'm guessing some prerequisites changed?

Getting message event

Is there a way for me to grab the message events that occurred inside of the function that actually sends the email? I get the response there for each email that is sent out but I need to be able to grab the message events for each email there as well so I can keep track of the time the message was actually sent out vs. when I tried to send it out.

Error setting value to 'FirstSentAt' when getting Subaccount Info

Hi,

I found an error, when I'm trying to get info account like this:

var infoSubaccount = api.Subaccounts.Info(ID_ACCOUNT);

An exception is thrown: {"Error setting value to 'FirstSentAt' on 'Mandrill.Model.MandrillSubaccountInfo'."}

With Fiddler, I can look the Mandrill API response and the returned value of first_sent_at is:
,"sent_total":297,"first_sent_at":"2015-03-28 19:12:01.97852","hourly_quota":312,

Thanks.
Regards,
David

SendAsync - Returns MandrillException 100

Hi,

Having recently switched to using this package (previously was using shawnmclean/Mandrill-dotnet) I'm randomly seeing the below exception when calling Messages.SendAsync:

Mandrill.Model.MandrillException: status: error, code: -100, name: GeneralError, message: An unknown error occurred processing your request. Please try again later.

I believe that this might be related to the volume of calls being made to Mandrill from within our infrastructure.

Can anyone confirm if this is the most likely reason and if there are any recommendations for mitigating this?

TIA
Ian

WebHookSignatureHelper.VerifyWebHookSignature was not validating the signature

Just wanted to mention that the following function
WebHookSignatureHelper.VerifyWebHookSignature(signature, authKey, new Uri(DisplayUrl), form);
requires a Uri object.

The signature does not validate when we use a Uri, but if we use a string of the exact URL that the Mandrill webhook calls, the validation will succeed.

StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(DisplayUrl);

not
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(new Uri(DisplayUrl));

I hope this helps!

Mandrill Username?

I have this working on a dev box but not sure how it works without a mandrill username?
I also assume that it uses SSL and smpt.mandrillapp.com on port 587

How to read response and error response from API integration

Hi Team,

We are integrating the mandrill API for sending the mail and using the below code for the same.
Here how can I read the successful response and error response. Here in case of error it is not going to catch block, if I pass the invalid API key.

Please share the demo code, if you have any.

try
{
var api = new MandrillApi("0xxxxxxxxxxxxxxxxxxQ");
var message = new MandrillMessage("[email protected]", "[email protected]",
"hello mandrill!", "...how are you?");
var result = api.Messages.SendAsync(message);

            IList<MandrillSendMessageResponse> response = result.Result;
        }
        catch (WebException ex)
        {
         }

Thanks,

Error : Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}

Hello,

I had tried to implement this code but mail not sent .

the result have like this
result = Id = 21, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

Please find the code below:

var api = new MandrillApi("01d3e3f0ccb9a6acbb388d735b89e105-us16");
var message = new MandrillMessage("[email protected]", "[email protected]",
"hello mandrill!", "...how are you?");
//var result = await api.Messages.SendAsync(message);
var result = System.Threading.Tasks.Task.Run(async () => await api.Messages.SendAsync(message));

Please resolve it as soon as possible..

**Update: Wrong repo - my apologies.** Mandrill Serializer - Null Value Behavior potentially influencing Handlebar Template scoping in Each loops

We are currently using Mandrill.net to send transactional email, using Handlebar templates. When sending content for our desired template, the default serializer configured in Mandrill.net is ignoring null value fields: settings.NullValueHandling = NullValueHandling.Ignore; This means that the footprint of the elements in our merge variable content list can differ, depending on the values that are non-null. EX, a list of object's with properties A, B, C and D may look like:

[
	{
		"A": "A content",
		"D": "D content"
	},
	{
		"A": "A content",
		"B": "B content"
	},
	{
		"B": "B new content",
		"C": "C content"
	}
]

We have noticed that when this is the case, the Handlebars template engine in Mandrill will "hold onto values" out of scope of the current loop variable, if they are not defined as null. In this example, the first result would render with values A and D, correctly. The second value, however, would have values A, B, and D - even though D was not part of the second element of the list, etc. Ex:

A Content, D Content
A Content, B Content, D Content
A Content, B New Content, C Content, D Content

For us, this is a big issue - we are hoping that simply passing null's into Mandrill will prevent, but are still looking into solutions at this time. Does anyone have any ideas on ways to prevent this scoping issue? Would it be possible to override the serializer used by Mandrill.net without branching and/or configuring this as an optional setting? Help is very appreciated!

Thanks,
Matt Ramsey

Unable to change BaseUrl: Mandrill TSL uses port 465

In Mandrill.net/src/Mandrill.net/MandrillRequest.cs the base url is hard coded:
protected static readonly Uri BaseUrl = new Uri("https://mandrillapp.com/api/1.0/");

Please make this URL configurable by a config or possible to override. The reason why I want to change this is because Mandrill uses port 465 for TLS/SSL: See Mandrill Docs. This is not specified in the URL thus making the CreateHttpWebRequest(requestUri) use the default port 587.

To be honest I think this URL should not be hard coded at all. For example, use the ConfigurationManager.AppSettings[KEY] to check the web.config for the URL and use that when available.

HttpClient in MandrillRequest needs to be a singleton

It's best practice to use a HttpClient singleton in C# because it will hang on to connections. I have an API (asp.net core) running on azure and it keeps going down every time mandrill goes down this week. It's eating up connections and making my application unresponsive. Using a singleton could greatly help performance.

Here are a few links on the topic, the first being directly from microsoft:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client#create-and-initialize-httpclient

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Missing From Address does not throw any exceptions

Im not sure if this is a Mandrill Api issue or the lib, seeing this is just an httpclient wrapper I think the fault might fall on Mandrill Api

So the problem is if I SendAsync an email without a FromEmail address no errors are generated but the email basically disappears without a trace (does not actually get sent)

Any ideas on how to solve this?

Use of attachments

when I attach a byte[] to a Mandril message using

        var pdf = new MandrillAttachment("application/pdf", "Invoice", dataArray);
        
        message.Attachments.Add(pdf);
         await MandrillApi.Messages.SendTemplateAsync(message, TemplateName);

I get a pretty nasty error
Exception Info: System.Net.Http.HttpRequestException
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
at Mandrill.MandrillRequest+d__10.MoveNext()

Exception Info: Mandrill.Model.MandrillException
at Mandrill.MandrillRequest+d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at Mandrill.MandrillRequest+d__92[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) at System.Runtime.CompilerServices.TaskAwaiter1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult()
at Lakrids.Commerce.Notifications.Messages.Message+d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()

I did NOT base64 encode the attachment - that is done by the API right?
Should attachments be supported?

MandrillSyncEventReject.Sender is not a string anymore

Something must have changed on Mandrill's end. The Sender property is now an object that I turned into this class to get our webhook to work:

public SenderReputationStats? Sender { get; set; }

public class SenderReputationStats
{
public int Sent { get; set; }
public int Hard_Bounces {get; set;}
public int Soft_Bounces {get; set;}
public int Rejects {get; set;}
public int Complaints {get; set;}
public int Unsubs {get; set;}
public int Opens {get; set;}
public int Clicks {get; set;}
public int Unique_opens {get; set;}
public int Unique_clicks {get; set;}
public int Reputation {get; set;}
public string Address { get; set; }

  [JsonConverter(typeof(IsoDateTimeConverter))]
  public DateTime Created_at { get; set; }

}

Thanks!
Bonnie

Error System.Security.Permissions

when executing sending messages send me the following error? What can be the cause?

The type initializer for 'Mandrill.SystemWebMandrillRequest' threw an exception.-Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Template Sending out Multiple Emails

Hi,

I'm using your wrapper and trying to send out (via one API call) multiple emails utilizing receipt merge variables, but having no luck.

From the below, you can see I'm sending in a list of customer leads and trying to customize the body of the template email by recipient. However, only the last lead information is sent.

Do you know why it is disregarding the for loop of recipient merge variables? TIA!

public static async Task<object> SendMonthlyReminder(List<CallCenterLeadModel> leads, string 
 template)
        {
  MandrillApi api = new MandrillApi(apiKey);
    var mandrillMessage = new MandrillMessage();
         mandrillMessage.FromEmail = fromEmail;
          mandrillMessage.ReplyTo = replyToEmail;

      
        foreach (var lead in leads)
        {
            mandrillMessage.AddTo(lead.Account.Email);

            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "AEMAIL", lead.Account.Email ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "NAME", lead.Account.Name ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "AREA", lead.Account.Area.Name ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "DATE", lead.DateSent.ToShortDateString());

            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "FNAME", lead.Profile.FirstName ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "LNAME", lead.Profile.LastName ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "RESIDENTNAME", lead.Profile.ResidentFirstName + " " + lead.Profile.ResidentLastName ?? "");
            mandrillMessage.AddRcptMergeVars(lead.Account.Email, "SOURCE", lead.Source ?? "");

        }

        mandrillMessage.AutoHtml = true;
        mandrillMessage.PreserveRecipients = false;

        var sendAt = DateTime.Now.ToUniversalTime();
        var result = await api.Messages.SendTemplateAsync(mandrillMessage, template, null, true, null, sendAt);
        return result;
}

Newtonsoft dependency

The current version of the API requires version 12 of Newtonsoft.Json but it's not apparent that the APIs actually rely on any of the updated aspects of this library.

It would be better if the dependency requirement was the lowest supported version of the library rather than the highest. Under the current model we cannot update beyond v5 because we have other libraries that must use Newtonsoft.Json v11 (Azure Fn Apps).

System.Text

Is a System.Text compatible version on the roadmap ?

How to send different messages to same receipient?

I am looking for a way to send different/same messages to the list of receipeint. But my code is sending the same message only instead the different message from the List. I think due to AddRcptMergeVars which is merging the value based on email_id , while the email may be twice or more times in the list. Is there any way I can use this to send my same/different messages using single call. I can send using foreach, but that's 100 of calls to send separate message to each individual. So looking for a way to do this in batch using template and mergevars .

For example

internal async Task<IList<MandrillSendMessageResponse>> EmailAsync(List<Messages> messages)
        {
            var message = new MandrillMessage
            {
                FromEmail = "from id",            
                PreserveRecipients = false
            };

            foreach (var email in messages)
            {
                MandrillMailAddress address = new MandrillMailAddress
                {
                    Type = MandrillMailAddressType.To,
                    Email = email.to
                };
                message.To.Add(address);

                message.AddRcptMergeVars(email.to, "Subject", email.subject);
                message.AddRcptMergeVars(email.to, "Body", email.body);
            }
            var result = await GetMandrillClient().Messages.SendTemplateAsync(message, "my-template");
            return result;
        }

image

Issue null variables and boolean variables

Hi!
There is an issue about this:
I call:
var result = await mandrillApi.Messages.SendTemplateAsync(message, "ToVault", contentList, true, "Main Pool");
The message is "sent" as I see in "result" but in mandrill dashboard nothing happens and i don´t get the email message in my inbox.
I test using Postman and i realize that:
The code sent by me that works is like:

"message": {
"from_email": "[email protected]",
"subject": "Surprise!",
"return_path_domain": "null",
"to": [
{
"email": "[email protected]",
"name": "Super Vault",
"type": "to"
}
],"merge": "true"
}

With the above code it works and I get an email in my inbox, mandrill dashboard shows that message.

But when i call var result = await mandrillApi.Messages.SendTemplateAsync(message, "ToVault", contentList, true, "Main Pool");
check the API log in mandrill and the request is like:

"message": {
"from_email": "[email protected]",
"subject": "Surprise!",
"to": [
{
"email": "[email protected]",
"name": "Super Vault",
"type": "to"
}
],"merge": true
}

The Issue here is:

1.- The boolean vars appear like true or false and not like "true" or "false"
2.- The vars that have assigned "null" don´t show in the request.

Those things make the email message is not sent.

Could you help me please?

Passing CC option has sent separate email instead of carbon copy.

I have tried to send emails using the mandrill.net library and it worked fine for sending emails for a single email.
But when I tried to send an email with a cc option it has sent two different emails.

First I created a mandril message and added required fields.

var api = new MandrillApi(apiKey);
var message = new MandrillMessage();
message.FromEmail = "email from";
message.AddTo("email to");
message.Subject = "the subject";
message.AddGlobalMergeVars("body", "the body");
message.AddTo("cc email address", string.Empty, MandrillMailAddressType.Cc);

api.Messages.SendTemplateAsync(message, "email template of mandrill");

Has anyone faced the same issue or solved the issue like this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.