Using CRM 4.0 SDK to send emails to multiple contacts at once - email

Is it possible to send out an email with multiple email addresses specified in the "to" field? I have it working for single recipients, but can't figure out how to send to multiple, here is my current code for emailing a single user:
public static void sendCRMNotification(string userGuid, string emailSubject, string emailBody, string recipientType)
{
//Set up CRM service
crmService crmservice = GetCrmService();
// Create a FROM activity party for the email.
activityparty fromParty = new activityparty();
fromParty.partyid = new Lookup();
fromParty.partyid.type = EntityName.systemuser.ToString();
fromParty.partyid.Value = new Guid(/*guid of sending user*/);
//Create a TO activity party for email
activityparty toParty = new activityparty();
toParty.partyid = new Lookup();
toParty.partyid.type = EntityName.contact.ToString();
toParty.partyid.Value = new Guid(userGuid);
//Create a new email
email emailInstance = new email();
//set email parameters
emailInstance.from = new activityparty[] { fromParty };
emailInstance.to = new activityparty[] { toParty };
emailInstance.subject = emailSubject;
emailInstance.description = emailBody;
//Create a GUId for the email
Guid emailId = crmservice.Create(emailInstance);
//Create a SendEmailRequest
SendEmailRequest request = new SendEmailRequest();
request.EmailId = emailId;
request.IssueSend = true;
request.TrackingToken = "";
//Execute request
crmservice.Execute(request);
}

This is what I have done in the past. Create the array in the beginning before you set it to the email property.
activityparty[] toParty = new activityparty[2];
toParty[0] = new activityparty();
toParty[0].partyid = new Lookup(EntityName.contact.ToString(), userGuid);
toParty[1] = new activityparty();
toParty[1].partyid = new Lookup(EntityName.contact.ToString(), anotherUserGuid);
emailMessage.to = toParty;

Related

How to send multiple email with attachments using send grid

I'm using the send grid api to send emails in my c# app, and I can't seem to figure out how to send an email with multiple attachments. I can send an email with a single attachement, but not multiple. I can see that there are four methods used for attachments(see below), but there is only one that allow you to send a list of attachements "IEnumerable attachments", however it's a return type is void. Can someone tell me how to send multiple attachments using the send gris api?
[![Send Grid methods for addding attachments](https://i.stack.imgur.com/Obf3n.png)](https://i.stack.imgur.com/Obf3n.png)
public async Task<SendResponse> SendHTMLWithAttachmentSendgrid(List<EmailAddress> recipientEmailList, string subject, string htmlContent, string[] attachmentFilePaths, bool showAllRecipients = false)
{
SendResponse emailResponse = new SendResponse();
try
{
List<SendGrid.Helpers.Mail.Attachment> attachments = new List<SendGrid.Helpers.Mail.Attachment>();
SendGrid.Helpers.Mail.Attachment attach = null;
//The total size of your email, including attachments, must be less than 30MB.
foreach (string item in attachmentFilePaths)
{
var stream = File.OpenRead(item);
//string[] contentArray = fileName.Split('.');
//string contentType = contentArray[1].ToString();
var streamCount = stream.ToString();
System.IO.BinaryReader br = new System.IO.BinaryReader(stream);
byte[] bytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
string[] filePathArray = item.Split('\\');
string fileName = filePathArray.LastOrDefault();
attach = new SendGrid.Helpers.Mail.Attachment() { Filename = fileName, Content= base64String };
attachments.Add(attach);
}
var from = new EmailAddress(DefaultSenderEmailAddress);
var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientEmailList, subject, string.Empty, htmlContent, showAllRecipients = false);
MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientEmailList, subject, string.Empty, htmlContent, showAllRecipients = false).AddAttachments(attachments);
var response = await this.SendGridClient.SendEmailAsync(msg);
}
catch (Exception ex)
{
_logger.LogError($"The following error occurred:{ex.Message}.");
}
return emailResponse;
}
I'm expecting to send multiple attachments in my email, using the Send Grid Api

How to get IFormFile data into stream to add as Email Attachment

I have an Email Razor page that accesses a custom method to send and email. All code seems to be correct. The problem I am having is accessing the "IFormFile files". I have tried adding the code to a controller as well as adding the IFormFile files to the custom method. I just can seem to find the right way to hande IFormFile. Below is the code that I currently have. What I am looking for is to see if someone can help me with the IFormFile portion. The information on IFormFile that I have found hasn't helped me so far as it's usually only partial information...I am very new to MVC and IFormFile, so help is greatly appreciated!
private async Task SendEmail()
{
try
{
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(sender));
email.To.Add(MailboxAddress.Parse(receiver));
email.Subject = emailsubject;
var multipart = new Multipart("mixed");
multipart.Add(new TextPart(TextFormat.Html) { Text = emailMessage });
foreach (var attachment in file)
{
var content = new MemoryStream();
attachment.CopyTo(content);
content.Position = 0;
var contentType = ContentType.Parse(attachment.ContentType);
var part = new MimePart(contentType.MimeType)
{
FileName = Path.GetFileName(attachment.FileName),
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent(content),
};
multipart.Add(part);
}
email.Body = multipart;
//email.Body = new TextPart(TextFormat.Html) { Text = emailMessage};
// send email
using var smtp = new SmtpClient();
smtp.Connect(outgoingServer, outgoingPort, SecureSocketOptions.Auto);
smtp.Authenticate(userName, userPassword);
smtp.Send(email);
smtp.Disconnect(true);
}
catch (Exception ex)
{
NotificationService.Notify(NotificationSeverity.Error, "Send Email Error!", ex.Message, 7000);
}
}

Mandrill.Net Adding Multiple Attachments

I am trying to send an email via Mandrill.Net, and am getting stuck trying to add multiple attachments. I have got the following code that create the list of attachments as IEnumerable, but I am getting the error
Unable to cast object of type 'System.Collections.Generic.List`1[Mandrill.Models.Attachment]' to type 'System.Collections.Generic.IEnumerable`1[Mandrill.Models.EmailAttachment]'.
The code is below:
try
{
EmailService ems = new EmailService();
EmailMessage msg = new EmailMessage();
List<EmailAddress> ToAdd = new List<EmailAddress>();
EmailAddress MainTo = new EmailAddress();
MainTo.Email = qe.ToAddress;
MainTo.Type = "bcc";
ToAdd.Add(MainTo);
msg.FromEmail = qe.FromAddress;
msg.FromName = qe.FromName;
msg.AddHeader("Reply-To", qe.ReplyTo);
msg.To = ToAdd;
msg.Subject = qe.Subject;
msg.Html = qe.Body;
msg.TrackClicks = true;
msg.TrackOpens = true;
// Need to add in Email Attachments
List<EmailAttachment> lea = new QueuedEmailModels().GetEmailAttachmentsByQueuedEmailID(qe.QueuedEmailsID); // Gets List of Attachments in DB
List<Attachment> lma = new List<Attachment>();
foreach(BRPA.EmailAttachment ea in lea)
{
byte[] array = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/UploadedFiles/" + ea.AttachmentID));
Attachment at = new Attachment
{
Content = Convert.ToBase64String(array),
Name = ea.AttachmentName,
Type = ""
};
lma.Add(at);
}
msg.Attachments = (IEnumerable<Mandrill.Models.EmailAttachment>)lma.AsEnumerable();
// End of Attachments
await ems.SendMailviaMandrill(msg);
qe.Status = "Sent";
qe.DateTimeSent = DateTime.Now.AddHours(2);
await ctx.SaveChangesAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Thanks
Paul
Oops - Found the answer.
I had a class for EmailAttachment that was overriding the Mandrill.Models.EmailAttachment.
Specified the full name and all is good.

Get Payer Email from Webhook Event

How can I retrieve the payers email address from a webhook event using the .NET SDK? I need the email to create a purchase with LeadDyno.
UPDATE
Here's how you do it...
var requestBody = string.Empty;
using (var reader = new StreamReader(HttpContext.Request.InputStream))
{
requestBody = reader.ReadToEnd();
}
JObject webhookEvent = JObject.Parse(requestBody);
payerEmail = webhookEvent["resource"]["payer"]["payer_info"]["email"].ToString();

Sending Gmail through C# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Sending Email in .NET Through Gmail
I have so many problems with sending mail through C#. I have tried forever on multiple apps and it never works....
Could someone PLEASE post some sample code that clearly labels where the sender and recipient go and offers help with the smtp sever dat or whatever!!
Something like this:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("sender#gmail.com", "recipient#example.com", "subject", "body");
System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 465);
emailClient.Credentials = new System.Net.NetworkCredential("yourgmailusername", "yourpassword");
emailClient.Send(message);
Some code that I wrote some time ago for sending email through a webform:
//using System.Net.Mail;
MailMessage msg = new MailMessage();
msg.To.Add(RECIPIENT_ADDRESS); //note that you can add arbitrarily many recipient addresses
msg.From = new MailAddress(SENDER_ADDRESS, RECIPIENT_NAME, System.Text.Encoding.UTF8);
msg.Subject = SUBJECT
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = //SOME String
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(ADDRESS, PASSWORD);
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (SmtpException ex)
{
throw; //or handle here
}
I made this class to send via my gmail account when in my dev environment and use the SMTP in my Web.Config when in production. Essentially the same as noblethrasher with some deployment comfort.
There is a flag for "mailConfigTest"
/// <summary>
/// Send Mail to using gmail in test, SMTP in production
/// </summary>
public class MailGen
{
bool _isTest = false;
public MailGen()
{
_isTest = (WebConfigurationManager.AppSettings["mailConfigTest"] == "true");
}
public void SendMessage(string toAddy, string fromAddy, string subject, string body)
{
string gmailUser = WebConfigurationManager.AppSettings["gmailUser"];
string gmailPass = WebConfigurationManager.AppSettings["gmailPass"];
string gmailAddy = WebConfigurationManager.AppSettings["gmailAddy"];
NetworkCredential loginInfo = new NetworkCredential(gmailUser, gmailPass);
MailMessage msg = new MailMessage();
SmtpClient client = null;
if (_isTest) fromAddy = gmailAddy;
msg.From = new MailAddress(fromAddy);
msg.To.Add(new MailAddress(toAddy));
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
if (_isTest)
{
client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
}
else
{
client = new SmtpClient(WebConfigurationManager.AppSettings["smtpServer"]);
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
}