示例#1
0
        private static IMessageAttachmentsCollectionPage ToFileAttachmentList(string attachments)
        {
            var fileList = new MessageAttachmentsCollectionPage();

            foreach (string attachment in attachments.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
            {
                byte[] contentBytes   = System.IO.File.ReadAllBytes(attachment);
                var    attachmentName = attachment.Split('\\');

                string contentType = MimeMapping.GetMimeMapping(attachmentName[attachmentName.Length - 1]);

                var fileAttachment = new FileAttachment
                {
                    ODataType       = "#microsoft.graph.fileAttachment",
                    Name            = Path.GetFileName(attachment),
                    ContentLocation = attachment,
                    ContentBytes    = contentBytes,
                    ContentType     = contentType
                };

                fileList.Add(fileAttachment);
            }

            return(fileList);
        }
        // Send an email message with a file attachment.
        // This snippet sends a message to the current user on behalf of the current user.
        public async Task <List <ResultsItem> > SendMessageWithAttachment()
        {
            List <ResultsItem> items = new List <ResultsItem>();

            // Create the recipient list. This snippet uses the current user as the recipient.
            User me = await graphClient.Me.Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).Select("Mail, UserPrincipalName").GetAsync();

            string address = me.Mail ?? me.UserPrincipalName;
            string guid    = Guid.NewGuid().ToString();

            List <Recipient> recipients = new List <Recipient>();

            recipients.Add(new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = address
                }
            });

            // Create an attachment and add it to the attachments collection.
            MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath("/Content/test.png")),
                ContentType  = "image/png",
                Name         = "test.png"
            });

            // Create the message.
            Message email = new Message
            {
                Body = new ItemBody
                {
                    Content     = Resource.Prop_Body + guid,
                    ContentType = BodyType.Text,
                },
                Subject      = Resource.Prop_Subject + guid.Substring(0, 8),
                ToRecipients = recipients,
                Attachments  = attachments
            };

            // Send the message.
            await graphClient.Me.SendMail(email, true).Request(requestOptions).WithUserAccount(ClaimsPrincipal.Current.ToGraphUserAccount()).PostAsync();

            items.Add(new ResultsItem
            {
                // This operation doesn't return anything.
                Properties = new Dictionary <string, object>
                {
                    { Resource.No_Return_Data, "" }
                }
            });
            return(items);
        }
        // Send an email message from the current user.
        public async Task SendEmail(string bodyHtml, string recipients)
        {
            try
            {
                if (recipients == null)
                {
                    return;
                }
                var attachments = new MessageAttachmentsCollectionPage();
                try
                {
                    var pictureStream = await GetMyPictureStream();

                    var pictureMemoryStream = new MemoryStream();
                    await pictureStream.CopyToAsync(pictureMemoryStream);

                    attachments.Add(new FileAttachment
                    {
                        ODataType    = "#microsoft.graph.fileAttachment",
                        ContentBytes = pictureMemoryStream.ToArray(),
                        ContentType  = "image/png",
                        Name         = "me.png"
                    });
                }
                catch (Exception e) { if (e.Message != "ResourceNotFound")
                                      {
                                          throw;
                                      }
                }

                // Prepare the recipient list.
                var splitRecipientsString = recipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                var recipientList         = splitRecipientsString.Select(recipient => new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = recipient.Trim()
                    }
                }).ToList();

                // Build the email message.
                var email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = bodyHtml,
                        ContentType = BodyType.Html,
                    },
                    Subject      = "Sent from the Microsoft Graph Connect sample",
                    ToRecipients = recipientList,
                    Attachments  = attachments
                };

                await _graphClient.Me.SendMail(email, true).Request().PostAsync();
            }
            catch (Exception e) { throw new EutGraphException("Error while sending email", e); }
        }
    private IMessageAttachmentsCollectionPage GetAttachments(MList <EmailAttachmentEmbedded> attachments)
    {
        var result = new MessageAttachmentsCollectionPage();

        foreach (var a in attachments)
        {
            result.Add(new FileAttachment
            {
                ContentId    = a.ContentId,
                Name         = a.File.FileName,
                ContentType  = MimeMapping.GetMimeType(a.File.FileName),
                ContentBytes = a.File.GetByteArray(),
            });
        }
        return(result);
    }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <returns></returns>
        public ActionResult SetMail()
        {
            var client = Office365Helper.GetAuthenticatedClient();
            var claimsPrincipalCurrent = System.Security.Claims.ClaimsPrincipal.Current;

            var fromrecipient = new Microsoft.Graph.Recipient()
            {
                EmailAddress = new Microsoft.Graph.EmailAddress()
                {
                    Address = claimsPrincipalCurrent.Identity.Name,
                    Name    = claimsPrincipalCurrent.FindFirst("name").Value
                }
            };
            var toToRecipients = new List <Recipient>();

            toToRecipients.Add(fromrecipient);

            byte[] contentBytes = System.IO.File.ReadAllBytes(@"C:\test\300.jpg");
            string contentType  = "image/jpg";
            MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = contentBytes,
                ContentType  = contentType,
                ContentId    = "testing",
                Name         = "300.jpg"
            });
            Message email = new Message
            {
                Body = new ItemBody
                {
                    Content     = "测试邮件这是一个测试邮件",
                    ContentType = BodyType.Text,
                },
                Subject      = "大会测试邮件",
                ToRecipients = toToRecipients,
                Attachments  = attachments
            };
            var d = client.Me.SendMail(email, true).Request().PostAsync();

            return(View());
        }
        // Send an email message from the current user.
        public static async Task SendEmail(GraphServiceClient graphClient, IHostingEnvironment hostingEnvironment, string recipients, HttpContext httpContext)
        {
            if (recipients == null)
            {
                return;
            }

            var attachments = new MessageAttachmentsCollectionPage();

            try
            {
                // Load user's profile picture.
                var pictureStream = await GetMyPictureStream(graphClient, httpContext);

                if (pictureStream != null)
                {
                    // Copy stream to MemoryStream object so that it can be converted to byte array.
                    var pictureMemoryStream = new MemoryStream();
                    await pictureStream.CopyToAsync(pictureMemoryStream);

                    // Convert stream to byte array and add as attachment.
                    attachments.Add(new FileAttachment
                    {
                        ODataType    = "#microsoft.graph.fileAttachment",
                        ContentBytes = pictureMemoryStream.ToArray(),
                        ContentType  = "image/png",
                        Name         = "me.png"
                    });
                }
            }
            catch (Exception e)
            {
                switch (e.Message)
                {
                case "ResourceNotFound":
                    break;

                default:
                    throw;
                }
            }

            // Prepare the recipient list.
            var splitRecipientsString = recipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var recipientList         = splitRecipientsString.Select(recipient => new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = recipient.Trim()
                }
            }).ToList();

            // Build the email message.
            var email = new Message
            {
                Body = new ItemBody
                {
                    Content     = System.IO.File.ReadAllText(hostingEnvironment.WebRootPath + "/email_template.html"),
                    ContentType = BodyType.Html,
                },
                Subject      = "Sent from the Microsoft Graph Connect sample",
                ToRecipients = recipientList,
                Attachments  = attachments
            };

            await graphClient.Me.SendMail(email, true).Request().PostAsync();
        }
        public async Task SendEmailAsync(string sendTo, string subject, string emailTemplate)
        {
            if (sendTo == null)
            {
                return;
            }

            var attachments = new MessageAttachmentsCollectionPage();

            try
            {
                // Load user's profile picture.
                var pictureStream = await GraphClient.Me.Photo.Content.Request().GetAsync();

                // Copy stream to MemoryStream object so that it can be converted to byte array.
                var pictureMemoryStream = new MemoryStream();
                await pictureStream.CopyToAsync(pictureMemoryStream);

                // Convert stream to byte array and add as attachment.
                attachments.Add(new FileAttachment
                {
                    ODataType    = "#microsoft.graph.fileAttachment",
                    ContentBytes = pictureMemoryStream.ToArray(),
                    ContentType  = "image/png",
                    Name         = "me.png"
                });
            }
            catch (ServiceException ex)
            {
                switch (ex.Error.Code)
                {
                case "Request_ResourceNotFound":
                case "ResourceNotFound":
                case "ErrorItemNotFound":
                case "itemNotFound":
                    throw;

                case "TokenNotFound":
                    //await HttpContext.ChallengeAsync();
                    throw;

                default:
                    throw;
                }
            }

            // Prepare the recipient list.
            var splitRecipientsString = sendTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var recipientList         = splitRecipientsString.Select(recipient => new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = recipient.Trim()
                }
            }).ToList();

            // Build the email message.
            var email = new Message
            {
                Body = new ItemBody
                {
                    Content     = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + emailTemplate),
                    ContentType = BodyType.Html,
                },
                Subject      = subject,
                ToRecipients = recipientList,
                Attachments  = attachments
            };

            await GraphClient.Me.SendMail(email, true).Request().PostAsync();
        }
        // Create the email message.
        public async Task <Message> BuildEmailMessage(GraphServiceClient graphClient, string recipients, string subject)
        {
            // Get current user photo
            Stream photoStream = await GetCurrentUserPhotoStreamAsync(graphClient);


            // If the user doesn't have a photo, or if the user account is MSA, we use a default photo

            if (photoStream == null)
            {
                photoStream = System.IO.File.OpenRead(System.Web.Hosting.HostingEnvironment.MapPath("/Content/test.jpg"));
            }

            MemoryStream photoStreamMS = new MemoryStream();

            // Copy stream to MemoryStream object so that it can be converted to byte array.
            photoStream.CopyTo(photoStreamMS);

            DriveItem photoFile = await UploadFileToOneDrive(graphClient, photoStreamMS.ToArray());

            MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = photoStreamMS.ToArray(),
                ContentType  = "image/png",
                Name         = "me.png"
            });

            Permission sharingLink = await GetSharingLinkAsync(graphClient, photoFile.Id);

            // Add the sharing link to the email body.
            string bodyContent = string.Format(Resource.Graph_SendMail_Body_Content, sharingLink.Link.WebUrl);

            // Prepare the recipient list.
            string[]         splitter = { ";" };
            string[]         splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            List <Recipient> recipientList         = new List <Recipient>();

            foreach (string recipient in splitRecipientsString)
            {
                recipientList.Add(new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = recipient.Trim()
                    }
                });
            }

            // Build the email message.
            Message email = new Message
            {
                Body = new ItemBody
                {
                    Content     = bodyContent,
                    ContentType = BodyType.Html,
                },
                Subject      = subject,
                ToRecipients = recipientList,
                Attachments  = attachments
            };

            return(email);
        }
示例#9
0
        /// <summary>
        /// Compose and send a new email.
        /// </summary>
        /// <param name="subject">The subject line of the email.</param>
        /// <param name="bodyContent">The body of the email.</param>
        /// <param name="recipients">A semicolon-separated list of email addresses.</param>
        /// <returns></returns>
        public static async Task ComposeAndSendMailAsync(string subject,
                                                         string bodyContent,
                                                         string recipients)
        {
            // Get current user photo
            Stream photoStream = await GetCurrentUserPhotoStreamAsync();


            // If the user doesn't have a photo, or if the user account is MSA, we use a default photo

            if (photoStream == null)
            {
                photoStream = new FileStream("test.jpg", FileMode.Open);
            }

            MemoryStream photoStreamMS = new MemoryStream();
            // Copy stream to MemoryStream object so that it can be converted to byte array.
            await photoStream.CopyToAsync(photoStreamMS);

            photoStream.Close();

            DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());

            MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = photoStreamMS.ToArray(),
                ContentType  = "image/png",
                Name         = "me.png"
            });

            // Get the sharing link and insert it into the message body.
            Permission sharingLink = await GetSharingLinkAsync(photoFile.Id);;

            string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl);

            // Prepare the recipient list
            string[]         splitter = { ";" };
            var              splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            List <Recipient> recipientList         = new List <Recipient>();

            foreach (string recipient in splitRecipientsString)
            {
                recipientList.Add(new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = recipient.Trim()
                    }
                });
            }

            try
            {
                var email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = bodyContentWithSharingLink,
                        ContentType = BodyType.Html,
                    },
                    Subject      = subject,
                    ToRecipients = recipientList,
                    Attachments  = attachments
                };

                try
                {
                    await _graphServiceClient.Me.SendMail(email, true).Request().PostAsync();
                }
                catch (ServiceException exception)
                {
                    throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
                }
            }

            catch (Exception e)
            {
                throw new Exception("We could not send the message: " + e.Message);
            }
        }
示例#10
0
        public async Task SendEmailAsync(string recipientAddress, string subject, string messageContent, StorageFile[] files)
        {
            try
            {
                // Create attachments
                var attachments = new MessageAttachmentsCollectionPage();
                foreach (var file in files)
                {
                    using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
                    {
                        var contentBytes = new byte[stream.Size];
                        using (DataReader reader = new DataReader(stream))
                        {
                            await reader.LoadAsync((uint)stream.Size);

                            reader.ReadBytes(contentBytes);
                        }

                        // Attach log file
                        attachments.Add(new FileAttachment
                        {
                            ODataType    = "#microsoft.graph.fileAttachment",
                            ContentBytes = contentBytes,
                            ContentType  = "application/octet-stream",
                            ContentId    = file.Name,
                            Name         = file.Name,
                        });
                    }
                }

                // Construct email
                var recipients = new List <Recipient>
                {
                    new Recipient()
                    {
                        EmailAddress = new EmailAddress()
                        {
                            Address = recipientAddress
                        }
                    },
                };

                Message email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = messageContent,
                        ContentType = BodyType.Text,
                    },
                    Subject      = subject,
                    ToRecipients = recipients,
                    Attachments  = attachments,
                };

                await SendEmailAsync(email);
            }
            catch (Exception ex)
            {
                LogService.Write(ex.ToString(), LoggingLevel.Error);
                throw;
            }
        }
示例#11
0
        static async Task Main(string[] args)
        {
            var userid = "f51bd33a-2d64-4b09-9b85-7c4efc24b16c";
            GraphServiceClient graphClient = GetAuthenticatedGraphClient();
            var mailboxhelper = new MailboxHelper(graphClient);

            Console.WriteLine("FRom Inbox");
            //List<Message> inboxitems = mailboxhelper.ListInboxMessages(userid, "test").Result;
            List <Message> inboxitems = mailboxhelper.ListInboxMessages(userid, string.Empty).Result;

            foreach (var item in inboxitems)
            {
                if (item.HasAttachments == true)
                {
                    var mailattachments = mailboxhelper.GetInboxMessageAttachments(userid, item.Id).Result;
                    if (mailattachments != null)
                    {
                        foreach (var mailattachment in mailattachments)
                        {
                            Console.WriteLine(mailattachment.Name);
                        }
                    }
                }
            }
            Console.WriteLine("FRom Sent Items");
            //List<Message> sentitems = mailboxhelper.ListSentMessages(userid, "string").Result;
            List <Message> sentitems = mailboxhelper.ListSentMessages(userid, string.Empty).Result;

            foreach (var item in sentitems)
            {
                if (item.HasAttachments == true)
                {
                    List <Attachment> mailattachments = mailboxhelper.GetMessageAttachments(userid, item.Id).Result;
                    if (mailattachments != null)
                    {
                        foreach (var mailattachment in mailattachments)
                        {
                            Console.WriteLine(mailattachment.Name);
                        }
                    }
                }
            }
            var toRec = new Recipient()
            {
                EmailAddress = new EmailAddress()
                {
                    Address = "*****@*****.**"
                }
            };

            byte[] contentBytes1 = System.IO.File.ReadAllBytes(@"C:\Users\dines\Downloads\AdvancedEnzyme.pdf");
            byte[] contentBytes2 = System.IO.File.ReadAllBytes(@"C:\Users\dines\Downloads\Lupin.pdf");
            IMessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = contentBytes2,
                ContentType  = "Application/pdf",
                Name         = "Lupin.pdf"
            });
            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = contentBytes1,
                ContentType  = "Application/pdf",
                Name         = "AdvancedEnzyme.pdf"
            });
            Message mailbody = new Message()
            {
                Body = new ItemBody()
                {
                    Content = Constants.getTemplate1("bkd1"), ContentType = BodyType.Html
                },
                Subject      = Constants.template1Subject,
                Attachments  = attachments,
                ToRecipients = new List <Recipient>()
                {
                    toRec
                }
            };

            await mailboxhelper.SendDKBSMail(userid, mailbody);
        }
示例#12
0
        public async Task <IActionResult> SendMail(EmailDTO emailDTO)
        {
            ServiceResponse <EmailDTO> Data = new ServiceResponse <EmailDTO>();

            try
            {
                #region ConvertToPdf
                HtmlToPdf converter = new HtmlToPdf();
                //create a new pdf document converting an url
                PdfDocument doc = converter.ConvertHtmlString(GeneratePDF.GetHtmlString(emailDTO));
                //save pdf document
                byte[] pdf = doc.Save();
                //close pdf document
                doc.Close();
                #endregion

                #region Get AzureAd Config
                var scopeFactory = this.HttpContext.RequestServices.GetService <IServiceScopeFactory>();
                using (var scope = scopeFactory.CreateScope())
                {
                    var serviceProvider = scope.ServiceProvider;
                    var options         = serviceProvider.GetRequiredService <AzureAdOptions>();
                    var optionsMail     = serviceProvider.GetRequiredService <SendMailOptions>();

                    #endregion

                    #region FileAttachment
                    MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
                    attachments.Add(new FileAttachment
                    {
                        ODataType    = "#microsoft.graph.fileAttachment",
                        ContentBytes = pdf,
                        ContentType  = BodyType.Text.ToString(),
                        ContentId    = "Piecejointe",
                        Name         = optionsMail.FileName
                    });
                    #endregion

                    #region Message
                    var message = new Message
                    {
                        Subject = optionsMail.Subject,
                        Body    = new ItemBody
                        {
                            ContentType = BodyType.Html,
                            Content     = "<div>Bonjour  " + emailDTO.VisiteDTO.Client.Nom + "   " + emailDTO.VisiteDTO.Client.Prenom + "  </div> <br/> <br/><div>" + Environment.NewLine + optionsMail.Body + " </div>"
                        },
                        ToRecipients = new List <Recipient>()
                        {
                            new Recipient
                            {
                                EmailAddress = new EmailAddress
                                {
                                    Address = emailDTO.VisiteDTO.Client.Courriel
                                }
                            }
                        }
                        ,
                        Attachments = attachments
                    };
                    #endregion

                    #region confidentialClient
                    IConfidentialClientApplication confidentialClient = ConfidentialClientApplicationBuilder
                                                                        .Create(options.ClientId)
                                                                        .WithClientSecret(options.ClientSecret)
                                                                        .WithAuthority(new Uri($"https://login.microsoftonline.com/{options.TenantId}/v2.0"))
                                                                        .Build();
                    #endregion

                    #region obtient un nouveau jeton
                    // Récupère un jeton d'accès pour Microsoft Graph (obtient un nouveau jeton si nécessaire).
                    var authResult = await confidentialClient
                                     .AcquireTokenForClient(options.Scopes)
                                     .ExecuteAsync().ConfigureAwait(false);

                    // Construise le client Microsoft Graph. En tant que fournisseur d'authentification, définissez un asynchrone
                    // qui utilise le client MSAL pour obtenir un jeton d'accès à l'application uniquement à Microsoft Graph,
                    // et insère ce jeton d'accès dans l'en-tête Authorization de chaque demande d'API.
                    var token = authResult.AccessToken;

                    GraphServiceClient graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) =>
                    {
                        //Ajoutez le jeton d'accès dans l'en-tête Authorization de la requête API.
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    })
                                                                                   );
                    #endregion

                    #region SendMail
                    await graphServiceClient.Me
                    .SendMail(message, false)
                    .Request()
                    .PostAsync();
                }
                #endregion
            }
            catch (Exception ex)
            {
                Data.Success  = false;
                Data.Messages = ex.Message;
            }
            return(Ok(Data));
        }
示例#13
0
        public async Task <IActionResult> AddMembers()
        {
            const string emailSender  = "*****@*****.**";
            const string emailSubject = ".NET Foundation: Please Activate Your Membership";
            const string redirectUrl  = "https://members.dotnetfoundation.org/Profile";

            string path         = Path.Combine(_hostingEnvironment.ContentRootPath, "MemberInvitation");
            string mailTemplate = await System.IO.File.ReadAllTextAsync(Path.Combine(path, "email-template.html"));

            var attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(await GetImageAttachement(path, "header.png"));
            attachments.Add(await GetImageAttachement(path, "footer.png"));

            const string groupId = "940ac926-845c-489b-a270-eb961ca4ca8f"; //Members

            //const string groupId = "6eee9cd2-a055-433d-8ff1-07ca1d0f6fb7"; //Test Members
            //We can look up the Members group by name, but in this case it's constant
            //var group = await _graphApplicationClient
            //        .Groups.Request().Filter("startswith(displayName,'Members')")
            //        .GetAsync();
            //string groupId = group[0].Id;

            //TODO Handle CSV upload rather than read from disk
            using (var reader = new StreamReader("MemberInvitation\\azure_ad_b2b.csv", Encoding.GetEncoding(1252)))
                using (var csv = new CsvReader(reader))
                {
                    var members = csv.GetRecords <ImportMember>();

                    //If we wanted to check if members are in the group first, could use this
                    //var existing = await _graphApplicationClient
                    //        .Groups[groupId]
                    //        .Members.Request().Select("id,mail").GetAsync();

                    foreach (var member in members)
                    {
                        Invitation invite = new Invitation();
                        invite.InvitedUserEmailAddress = member.EMail.Trim();
                        invite.SendInvitationMessage   = false;
                        invite.InviteRedirectUrl       = redirectUrl;
                        invite.InvitedUserDisplayName  = member.FirstName + " " + member.LastName;

                        var result = await _graphApplicationClient.Invitations.Request().AddAsync(invite);

                        try
                        {
                            await _graphApplicationClient
                            .Groups[groupId]
                            .Members.References.Request()
                            .AddAsync(result.InvitedUser);
                        }
                        catch (Exception ex)
                        {
                            //They're already added to the group, so we can break without sending e-mail
                            _logger.LogWarning("User exists: {FirstName} {LastName}: {EMail}", member.FirstName, member.LastName, member.EMail);
                            continue;
                        }

                        List <Recipient> recipients = new List <Recipient>();
                        recipients.Add(new Recipient
                        {
                            EmailAddress = new EmailAddress
                            {
                                Name    = member.FirstName + " " + member.LastName,
                                Address = member.EMail
                            }
                        });

                        // Create the message.
                        Message email = new Message
                        {
                            Body = new ItemBody
                            {
                                //TODO Replace with e-mail template
                                Content = mailTemplate
                                          .Replace("{{action}}", result.InviteRedeemUrl)
                                          .Replace("{{name}}", member.FirstName),
                                ContentType = BodyType.Html,
                            },
                            HasAttachments = true,
                            Attachments    = attachments,
                            Subject        = emailSubject,
                            ToRecipients   = recipients
                        };

                        // Send the message.
                        await _graphApplicationClient.Users[emailSender].SendMail(email, true).Request().PostAsync();
                        _logger.LogInformation("Invite: {FirstName} {LastName}: {EMail}", member.FirstName, member.LastName, member.EMail);
                    }
                }

            return(RedirectToAction(nameof(Index)));
        }
        public static string SendMail(string subject, string content, string toRecipients,
                                      string ccRecipients, string bccRecipients,
                                      WorkflowFile attachment)
        {
            // Check parameters
            if (string.IsNullOrEmpty(subject))
            {
                return("The subject is required");
            }
            if (string.IsNullOrEmpty(content))
            {
                return("The content is required");
            }
            if (string.IsNullOrEmpty(toRecipients))
            {
                return("Recipients are required");
            }

            try
            {
                // Prepare the recipient list
                string[]         splitter = { ";" };
                var              splitToRecipientsString  = toRecipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
                var              splitCcRecipientsString  = ccRecipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
                var              splitBccRecipientsString = bccRecipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
                List <Recipient> toRecipientList          = new List <Recipient>();
                List <Recipient> ccRecipientList          = new List <Recipient>();
                List <Recipient> bccRecipientList         = new List <Recipient>();

                foreach (string recipient in splitToRecipientsString)
                {
                    toRecipientList.Add(new Recipient {
                        EmailAddress = new EmailAddress {
                            Address = recipient.Trim()
                        }
                    });
                }
                foreach (string recipient in splitCcRecipientsString)
                {
                    ccRecipientList.Add(new Recipient {
                        EmailAddress = new EmailAddress {
                            Address = recipient.Trim()
                        }
                    });
                }
                foreach (string recipient in splitBccRecipientsString)
                {
                    bccRecipientList.Add(new Recipient {
                        EmailAddress = new EmailAddress {
                            Address = recipient.Trim()
                        }
                    });
                }

                MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

                if (attachment != null)
                {
                    attachments.Add(new FileAttachment
                    {
                        ODataType    = "#microsoft.graph.fileAttachment",
                        ContentBytes = attachment.Content,
                        ContentType  = attachment.ContentType,
                        Name         = attachment.Name
                    });
                }


                var email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = content,
                        ContentType = BodyType.Html,
                    },
                    Subject       = subject,
                    ToRecipients  = toRecipientList,
                    CcRecipients  = ccRecipientList,
                    BccRecipients = bccRecipientList,
                    Attachments   = attachments
                };

                try
                {
                    GraphClient.Users[ServiceAccountId].SendMail(email, true).Request().PostAsync().Wait();

                    return(Success);
                }
                catch (ServiceException exception)
                {
                    Log("[SendMail] Error - We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
                    return("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
                }
            }
            catch (Exception e)
            {
                Log("[SendMail] Error - We could not send the message: " + e.Message + " - InnerException : " + e.InnerException);
                return("We could not send the message: " + e.Message);
            }
        }