Iterate through a list of email addresses and send email microsoft graph c#
I am iterating through a data table of email addresses and sending an email using microsoft.graph and azure.identity. My code is working, but I don't think it is efficient. My issues are the following
- how do I know when the emails are finished sending - it just stays on the "Send Email" window
- I want emails to continue sending even if one or more in the list are in error (Do I just remove the try / catch?)
Please take a look at my code and make recommendations. I am not too familiar with the environment.
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using System.Windows.Forms;
using IBM.Data.DB2.iSeries;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Azure.Identity;
using System.Configuration;
using Microsoft.Graph.Users.Item.SendMail;
namespace HK_Emailer
{
public partial class Form1 : Form
{
DataTable dtEmail = new DataTable();
string htmlBody = "";
public Form1()
{
InitializeComponent();
}
public async void btnSend_Click(object sender, EventArgs e)
{
try
{
string un = ConfigurationManager.AppSettings["ALUsername"];
string pw = ConfigurationManager.AppSettings["ALPwd"];
iDB2Connection conn = new iDB2Connection("DataSource=xxx.xxx.xx.xx;UserID=" + un + ";Password=" + pw + ";DataCompression=True;");
conn.Open();
iDB2Command MyDB2Command = conn.CreateCommand();
//SQL query to get email addresses
MyDB2Command.CommandText = "select xxx as Email from xxx; "
iDB2DataAdapter adapter = new iDB2DataAdapter();
adapter.SelectCommand = MyDB2Command;
dtEmail.Clear();
adapter.Fill(dtEmail);
adapter.Dispose();
MyDB2Command.Dispose();
conn.Close();
await SendEmail("mailer@humkoop.co.za", dtEmail);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
static async Task SendEmail(string fromAddress, DataTable dtEmail)
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = ConfigurationManager.AppSettings["tenantId"];
var clientId = ConfigurationManager.AppSettings["clientId"];
var clientSecret = ConfigurationManager.AppSettings["clientSecret"];
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
string Subject = "Notice";
var htmlBody = System.IO.File.ReadAllText("Path of HTML for email");
// Attachment 1
var file1 = "path of attachment";
byte[] fileArray1 = System.IO.File.ReadAllBytes(@file1);
foreach (DataRow row in dtEmail.Rows)
{
string AddressTrim = row["Email"].ToString().Replace(" ", string.Empty);
var requestBody = new SendMailPostRequestBody
{
Message = new Microsoft.Graph.Models.Message
{
Subject = Subject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = htmlBody,
},
ToRecipients = new List