0

I have the following code as part of a console application:-

            using (ClientContext context = new ClientContext(scurl))
            {
                string s = "***the password***";
                SecureString passWord = new SecureString();
                foreach (var cc in s)
                passWord.AppendChar(cc);
                context.Credentials = new SharePointOnlineCredentials("admin.user@*****.onmicrosoft.com", passWord);    
                List oList = context.Web.Lists.GetByTitle(listname);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='ContractReviewDate'/>" +
                "<Value Type='DateTime'><Today /></Value></Eq><Eq><FieldRef Name='ContractStatus'/><Value Type='String'>Active</Value></Eq></AND></Where></Query><RowLimit>5000</RowLimit></View>";
                ListItemCollection collListItem = oList.GetItems(camlQuery);
                context.Load(collListItem,
                items => items.Include(
                item => item["ContractStatus"],
                item => item["PersonResponsible"]));
                context.ExecuteQuery();
                foreach (ListItem oListItem in collListItem)
                {
                    oListItem["ContractStatus"] = "Needs Review";
                    oListItem.Update();
                    context.ExecuteQuery();
                    var userValue =  (FieldUserValue)oListItem["PersonResponsible"];
                    var user = context.Web.GetUserById(userValue.LookupId);
                    context.Load(user, x => x.Email);
                    context.ExecuteQuery();
                    MailMessage mail = new MailMessage("no-reply@sharepointonline.com", user.Email);
                    SmtpClient client = new SmtpClient();
                    client.Port = 587;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.EnableSsl = true;
                    client.Host = "smtp.office365.com";
                    mail.Subject = "The Contract has revowed";
                    mail.Body = "this is my test email body";
                    client.Send(mail);
                }

            }

but i am getting exception on client.Send(mail);, as follow:-

System.Net.Mail.SmtpException was unhandled HResult=-2146233088
Message=Failure sending mail. Source=System StackTrace: at System.Net.Mail.SmtpClient.Send(MailMessage message) at ConsoleApplication1.Program.Main(String[] args) in c:\Users***\ConsoleApplication1\Program.cs:line 77 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.Net.WebException HResult=-2146233079 Message=Unable to connect to the remote server Source=System StackTrace: at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6) at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback) at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint) at System.Net.Mail.SmtpClient.GetConnection() at System.Net.Mail.SmtpClient.Send(MailMessage message) InnerException: System.Net.Sockets.SocketException HResult=-2147467259 Message=No connection could be made because the target machine actively refused it 52.97.165.146:587 Source=System ErrorCode=10061 NativeErrorCode=10061 StackTrace: at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) InnerException:

so can anyone advice on this please?

1

the way I see it, you are setting up a SMTPClient object but not supplying any credentials

so, either have set client.UseDefaultCredentials to true or use,

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
client.Credentials = credentials;

or use csom utilities to send the email instead [PS code],

$EmailProperties = New-Object Microsoft.SharePoint.Client.Utilities.EmailProperties
$EmailProperties.From = $EmailFrom
$EmailProperties.To = [String[]] $EmailTo
$EmailProperties.Subject = $Subject
[Microsoft.SharePoint.Client.Utilities.Utility]::SendEmail($Context,$EmailProperties)
$Context.ExecuteQuery()

more

https://stackoverflow.com/questions/2766928/how-to-set-username-and-password-for-smtpclient-object-in-net

Send Email from SharePoint Online using CSOM in PowerShell

https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-office-3

  • ok thanks will try your approach, but will your proposed approach allow me to send emails to external users? – SharePoint TestDev Nov 27 '19 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.