Click here to Skip to main content
16,022,069 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am trying to send email using office 365 smtp connection and i am having problem to configure it and sen email. hear is my coding in my .net core application.
I am not getting any error meassages but email is not sending

What I have tried:

public static int SendMail(string subject,string message,string toAddress, string CcAddress, string BCC)
		{
			int res = 0;
			try
			{
				string fromAddress = "support@domain.com";
				var credentials = new ClientSecretCredential(
									"<client ID>", "<tenent ID>", "<client secret>",
								new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud });
				GraphServiceClient graphServiceClient = new GraphServiceClient(credentials);


				string[] toMail = toAddress.Split(',');
				//-----
				Logger.Log(toAddress + "|| toaddress sendemail");
				//-----
				List<Recipient> toRecipients = new List<Recipient>();
				int i = 0;
				for (i = 0; i < toMail.Count(); i++)
				{
					Recipient toRecipient = new Recipient();
					EmailAddress toEmailAddress = new EmailAddress();

					toEmailAddress.Address = toMail[i];
					toRecipient.EmailAddress = toEmailAddress;
					toRecipients.Add(toRecipient);
				}

				List<Recipient> ccRecipients = new List<Recipient>();
				if (!string.IsNullOrEmpty(CcAddress))
				{
					string[] ccMail = CcAddress.Split(',');
					int j = 0;
					for (j = 0; j < ccMail.Count(); j++)
					{
						Recipient ccRecipient = new Recipient();
						EmailAddress ccEmailAddress = new EmailAddress();

						ccEmailAddress.Address = ccMail[j];
						ccRecipient.EmailAddress = ccEmailAddress;
						ccRecipients.Add(ccRecipient);
					}
				}
				var mailMessage = new Message
				{
					Subject = subject,
					
					Body = new ItemBody
					{
						ContentType = BodyType.Html,
						Content = message
					},
					ToRecipients = toRecipients,
					CcRecipients = ccRecipients

				};

				Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody body = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody()
				{
					Message = mailMessage,
					SaveToSentItems = false  // or true, as you want
				};

				// Send mail as the given user. 
				graphServiceClient
				   .Users[fromAddress]
					.SendMail
					.PostAsync(body);

				Logger.Log("Email Send Sucessful || SendEmail");
				res = 1;

			}
			catch (Exception ex)
			{
				Logger.Log(ex.Message + "|| Send Email Method");
				res = 0;
			}
			return res;
		}
Posted

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900