Mail Sending to multiple users in Dynamics CRM + Plugin - c#

I'm writing plugin C#, to send an email to the users who are under SystemCustomizer role notifying that Contact is creating or Updating.
How to send an email to multiple users (Bulkmailing/ forEach loop for creating mail request to every user)?

Use a query to find each system user entity with the system customiser role.
Then for each user send an email. 1; create the email, 2; send the email.
// Create an e-mail message.
Email email = new Email
{
To = new ActivityParty[] { toParty },
From = new ActivityParty[] { fromParty },
Subject = "SDK Sample e-mail",
Description = "SDK Sample for SendEmail Message.",
DirectionCode = true
};
_emailId = _serviceProxy.Create(email);
// Use the SendEmail message to send an e-mail message.
SendEmailRequest sendEmailreq = new SendEmailRequest
{
EmailId = _emailId,
TrackingToken = "",
IssueSend = true
};
SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);

Related

Sending emails between accounts using Microsoft Graph using Azure AD produces invalid IP error

I registered a daemon app in Azure AD and am creating a class to do some basic things like send and delete emails but I get an error when trying to send between two #*.onmicrosoft.com email boxes. I am able to send from Gmail to these emails for example but not between the two emails for some reason.
Error:
The way I am sending emails is as follows:
public async Task Send(string[] to, string subject, string body, FileInfo[] attachments = null, bool saveToSentItems = true, bool isBodyHTML = false)
{
var msg = new Message
{
Subject = subject,
Body = new ItemBody { ContentType = (isBodyHTML) ? BodyType.Html : BodyType.Text, Content = body },
ToRecipients = to.ToList().Select(x => new Recipient() { EmailAddress = new EmailAddress { Address = x } })
};
await graphClient.Users[email].SendMail(msg, saveToSentItems).Request().PostAsync();
}
So I think it's because of trial licenses and couldn't figure out way yet to turn off the IP filtering:

.NET : Unable to change from in SMTP email

I'm trying to send emails in .NET over SMTP. I linked serval custom aliases to the account in office365. (For example no-reply#domain-a.com, no-reply#domain-b.com)
But the mails arrive from No-Reply#mydomain.onmicrosoft.com. Even if I pass in a custom domain in the "from" parameter.
Here is my code:
var smtpClient = new SmtpClient(_settings.Endpoint, int.Parse(_settings.Port))
{
UseDefaultCredentials = false,
EnableSsl = true,
Credentials = new NetworkCredential(_settings.UserName, _settings.Password),
};
var mailMessage = new MailMessage
{
From = new MailAddress(message.From.Email, message.From.Name),
Subject = message.Subject,
Body = message.HtmlMessage,
IsBodyHtml = true
};
foreach (var addressee in message.Tos)
{
mailMessage.To.Add(addressee.Email);
}
try
{
smtpClient.Send(mailMessage);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending email");
throw;
}
As username I'm using myaccount#mydomain.onmicrosoft.com. What am I missing here?
Nothing should be wrong with the office365/domain config cause it works when I'm trying to send the mail using powershell
$O365Cred = Get-Credential #the myaccount#mydomain.onmicrosoft.com credentials
$sendMailParams = #{
From = 'no-reply#mydomain-a.com'
To = 'me#gmail.com'
Subject = 'some subject'
Body = 'some body'
SMTPServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $O365Cred
}
Send-MailMessage #sendMailParams
Both Google (GMail) and Microsoft (Office365) replace the From header with the email address of the account used to send the mail in order to curtail spoofing.
If you do not want this, then you'll need to use another SMTP server or set up your own.
I found out that it works when sending the email to my personal Gmail. Meaning that there is nothing wrong with the code, but a configuration problem in my office365 / AD domain.
Apparently the outlook "address book" automatically fills in the "from / sender" part in the email, caused because I was sending an mail to the same domain as the one used for my SMTP account. (for example me#domain-a.com and noreply#domain-a.com).

getting "Unknown Mailbox" error when sending email using EWS API (C#)

I'm simply trying to use the Office 365 API to send an email via the "Send()" function, but am getting back Microsoft.Exchange.Webservices.Data.ServiceResponseException: Mailbox does not exist.
Here's my exchange service:
_emailExchangeService =
new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Url = new Uri(_settings.ExchangeWebServiceEndpoint),
Credentials = new WebCredentials(_settings.AppEmailUserName, _settings.AppEmailPassword),
TraceEnabled = true,
UseDefaultCredentials = false
};
And here's the code I'm using to send the email:
public void SendEmail(MemoryStream attachment, string body, string subject, string recipients, string fromMailbox)
{
EmailMessage message = new EmailMessage(_emailExchangeService);
message.From = fromMailbox;
message.Subject = subject;
message.Body = new MessageBody(BodyType.Text, body);
message.ToRecipients.Add(recipients);
message.Attachments.AddFileAttachment("FileName", attachment);
message.Send();
}
What mailbox am I forgetting to define when sending this, the sent box? I thought the "from" field would define the mailbox for sending items. I'm just not even sure where to do that and my code looks identical to the docs.
Side note: I know the exchange service is set up correctly because if I define an inbox email address and attempt to FindItems(_inbox) on the mailbox, it works.

Send Reply with attachment using Microsoft Graph API

I've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.
You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.

cannot send emails with Amazon SES .NET SDK

I can send emails with SMTP option in .Net but I need to use .NET SDK to send emails via Amazon. It gives me error that says "Email address is not verified", event though I am sure that it is verified. By the way, I am using a Test Account(SandBox).
What am I doing wrong? or am I missing anything?
here is my code,
var sesClient = new AmazonSimpleEmailServiceClient("AKIAJHXXXXXXXXXXX", "RVGdbCKXILwjUIKSexKlwXXXXXXXXXXXX",Amazon.RegionEndpoint.USEast1);
var dest = new Destination
{
ToAddresses = new List<string>() { "tayfun.ural#aryxxx.com" },
CcAddresses = new List<string>() { "arif.yilmaz#aryxxx.com" }
};
var from = "tayfun.ural#aryxxx.com";
var subject = new Content("You're invited to the meeting");
var body = new Body(new Content("Please join us Monday at 7:00 PM."));
var msg = new Message(subject, body);
var request = new SendEmailRequest
{
Destination = dest,
Message = msg,
Source = from
};
var verify = sesClient.VerifyEmailAddress(new VerifyEmailAddressRequest { EmailAddress = "tayfun.ural#aryada.com" });
try
{
var response = sesClient.SendEmail(request);
}
catch (Exception ex)
{
throw ex;
}
When using Amazon SES in sandbox/test mode, all from/to/cc addresses must be verified email addresses. The error "Email address is not verified" means that atleast one of the email addresses is not verified. It could be the TO, FROM, CC, or BCC.
In your case, ensure that both "tayfun.ural#aryxxx.com" and "arif.yilmaz#aryxxx.com" are verified and/or that "aryxxx.com" is a verified domain.
String FROM = "SENDER#EXAMPLE.COM"; // Replace with your "From" address. This address must be verified.
String TO = "RECIPIENT#EXAMPLE.COM"; // Replace with a "To" address. If you have not yet requested
// production access, this address must be verified.
String SUBJECT = "Amazon SES test (AWS SDK for .NET)";
String BODY = "This email was sent through Amazon SES by using the AWS SDK for .NET.";
// Construct an object to contain the recipient address.
Destination destination = new Destination();
destination.ToAddresses = (new List<string>() { TO });
// Create the subject and body of the message.
Content subject = new Content(SUBJECT);
Content textBody = new Content(BODY);
Body body = new Body(textBody);
// Create a message with the specified subject and body.
Message message = new Message(subject, body);
// Assemble the email.
SendEmailRequest request = new SendEmailRequest(FROM, destination, message);
// Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
// access status, sending limits, and Amazon SES identity-related settings are specific to a given
// AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
// the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are USWest2
// and EUWest1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.USEast1;
// Instantiate an Amazon SES client, which will make the service call.
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(REGION);
// Send the email.
try
{
//("Attempting to send an email through Amazon SES by using the AWS SDK for .NET...");
client.SendEmail(request);
//("Email sent!");
}
catch (Exception ex)
{
//("The email was not sent.");
//("Error message: " + ex.Message);
}

Categories

Resources