How I can send emails using the client object model?

I have tried this, but I always get an exception with error message "A recipient must be specified.":
string webUrl = "http://sharepoint.example.com/";
EmailProperties properties = new EmailProperties();
properties.To = new string[] { "[email protected]" };
properties.Subject = "Test subject";
properties.Body = "Test body";
ClientContext context = new ClientContext(webUrl);
Utility.SendEmail(context, properties);
context.ExecuteQuery(); // ServerException thrown here
context.Dispose();
Server stack trace:
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Microsoft.SharePoint.Utilities.SPUtility.SendEmail_Client(EmailProperties properties)
at Microsoft.SharePoint.ServerStub.Utilities.SPUtilityServerStub.InvokeStaticMethod(String methodName, XmlNodeList xmlargs, ProxyContext proxyContext, Boolean& isVoid)
at Microsoft.SharePoint.Client.ServerStub.InvokeStaticMethodWithMonitoredScope(String methodName, XmlNodeList args, ProxyContext proxyContext, Boolean& isVoid)
at Microsoft.SharePoint.Client.ClientMethodsProcessor.InvokeStaticMethod(String typeId, String methodName, XmlNodeList xmlargs, Boolean& isVoid)
at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessStaticMethod(XmlElement xe)
at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessOne(XmlElement xe)
at Microsoft.SharePoint.Client.ClientMethodsProcessor.ProcessStatements(XmlNode xe)
at Microsoft.SharePoint.Client.ClientMethodsProcessor.Process()
msdn link: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.utilities.utility.sendemail.aspx

hi
if you will check the code of SendEmail_Client(EmailProperties properties), you will find that it may only send emails to internal users. May be it was made intentionally in order to prevent spamming from client code. So let's see:
internal static void SendEmail_Client(EmailProperties properties)
if (properties.To.Count == 0)
throw new SPException(SPResource.GetString(web.LanguageCulture, "SendEmailInvalidRecipients", new object[0]));
AddressReader func = null;
using (MailMessage mm = new MailMessage())
func = delegate (MailAddress a) {
mm.To.Add(a);
ResolveAddressesForEmail(web, properties.To, func);
new SmtpClient(SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address).Send(mm);
I.e. it adds recipient in ResolveAddressesForEmail() method. Now let's check this method:
private static void ResolveAddressesForEmail(SPWeb web, IEnumerable<string> addresses, AddressReader func)
if (addresses != null)
foreach (string str in addresses)
if (string.IsNullOrEmpty(str))
continue;
SPPrincipalInfo info = ResolvePrincipal(web, str, SPPrincipalType.All, SPPrincipalSource.All, null, false);
if ((info != null) && (info.PrincipalId > 0))
if (!string.IsNullOrEmpty(info.Email))
try
func(new MailAddress(info.Email, (info.DisplayName != null) ? info.DisplayName : "", Encoding.UTF8));
catch (FormatException)
continue;
if ((string.IsNullOrEmpty(info.Email) && info.IsSharePointGroup) && web.DoesUserHavePermissions(SPBasePermissions.BrowseUserInfo))
SPGroup byNameNoThrow = web.SiteGroups.GetByNameNoThrow(info.LoginName);
if (byNameNoThrow == null)
continue;
foreach (SPUser user in byNameNoThrow.Users)
if (!string.IsNullOrEmpty(user.Email))
try
func(new MailAddress(user.Email, (user.Name != null) ? user.Name : "", Encoding.UTF8));
continue;
catch (FormatException)
continue;
continue;
I.e. at first it tries to resolve user using ResolvePrincipal() method. If it is not resolved (info == null) email is not sent. But if it is - it first checks that email is not empty. If it is not - it adds email to the MailMessage.To recipients list. If
it is empty it checks whether the principal info represents Sharepoint group. If yes - it will send email to each member of the group.
So it may be so that you try to send email to external user (which is not supported according to the code above), or resolved principal doesn't have email specified.
Blog - http://sadomovalex.blogspot.com
CAML via C# - http://camlex.codeplex.com

Similar Messages

  • Error in Application.Run(DisplayLoginForm) and Remote Authentication in SharePoint Online Using the Client Object Model

    Hi guys
    I Think that is a simple error, but I don’t have enough knowledge in .NET apps.
    I make an console app that use Remote Authentication in SharePoint Online Using the Client Object Model, that a I downloaded from MSDN.
    This App run ok.
    But when I like to make a Windows From App. This component send me an error in Application.Run(DisplayLoginForm)
    This err msg :
     An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
    Additional information: Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
    Is there any way to use a form inside a windows form?
    Thank in advance
    Ramiro
    Ramiro B

    Hi,
    Based on the error message, please do as following:
    1. Check your code logic below:
    void btn_Click(object sender, System.EventArgs e)
    Thread t = new Thread(StartMyForm);
    t.TrySetApartmentState(ApartmentState.STA);
    t.Start();
    public static void StartMyForm()
    Application.Run(new MyForm(..));
    2.Try to add the following code line in your code.
    Application.Restart();
    If the issue still exists, please provide your requirement and code for a further research.
    Best Regards
    Dennis Guo
    TechNet Community Support

  • HT1668 I cannot remove the draft write mail template from the mail application screen. Save draft works but cancel does not remove the draft template. I can send email using the template but it remains on screen preventing me from accessing any mail

    Still can't get rid of the template page

    I am not at all sure about what you are calling a draft email template. I have never seen one in the mail app and unless this is something that you created in Pages or some other word processing program I don't know what template you are describing.
    Anyway, this may work. Quit the mail app and them go back and see if the draft is still on the screen.
    Quit the app completely and restart the iPad. Go to the home screen first by tapping the home button. Double tap the home button and the task bar will appear with all of your recent/open apps displayed at the bottom. Tap and hold down on any app icon until it begins to wiggle. Tap the minus sign in the upper left corner of the app that you want to close. Tap the home button or anywhere above the task bar.
    Or try this.
    Reset the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons

  • The remote server returned an error: (401) Unauthorized. while running client context using sharepoint client object model

    Hi,
    I have started using the client object model so that i do not have to go to sharepoint admins to perform some basic operations on remote server. While assigning list item level permission i am getting following error, could you please help. thanks.
    The remote server returned an error: (401) Unauthorized.
       at
    System.Net.HttpWebRequest.GetResponse()
       at
    Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
       at
    Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
       at
    Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
       at
    SetDowntimeItemPermission.SetPermission.Main(String[] args) in

    it seems your request was unauthenticated i'm not sure are you using a web application with FBA or desktop application my suggestion would be try to impersonate your request by passing network credentials (COM works on network credentials )
    NetworkCredential credentials = new NetworkCredential("username", "pwd", "domain");
    ClientContext context = new ClientContext("http://site-url");
    context.Credentials = credentials;
    Best Regards, Ashutosh | SharePoint World

  • SharePoint 2013 implement simple logout button which do not redirect to default sign out page using JavaScript client object model

    I am using windows authentication in my web application.
    My requirement is to implement a sign out button which will sign out the user without having him to close the browser and application should not ask him to login again.
    I tried following two options:
     1. Redirecting the user to default signout.aspx page " /_layouts/15/SignOut.aspx "
     2. Using "Sign In as a different user" URL " /_layouts/15/closeConnection.aspx?loginasanotheruser=true "
    In first case, user is redirected to default sign out page but he can press "Go Back to Site" link to revisit the site. Another major issue is that the user has to close the browser to sign out from the application completely, which is not desirable
    in my project requirement.
    In second case, the the current user is signed out of the application but if the user has saved the password in browser, he gets signed in automatically to the application.
    I also came across the solution where we replace the default sign out page with a custom sign out page, but I am not sure whether it can be implemented using JavaScript Client Object Model of SharePoint.

    Hi 
    I'm basically looking for the exact answer for the query.
    Meanwhile you need to go through the link mentioned below in order to understand how to do it.
    Debugging and Logging Capabilities in SharePoint 2010
    Indul Hassan
    Microsoft Community Contributor
    http://www.indulhassan.com
    You Snooze.. You Lose !!

  • How to remove error 59 which occurred while using Send Email Using Smtp Client .VI in Labview 2013.

    Hi,I am trying to run Send Email Using Smtp Client .VI in Labview 2013 examples ,but it gives error 59.Please can anyone suggest how to remove the error.The printscreen is attached below.
    Solved!
    Go to Solution.
    Attachments:
    error.docx ‏310 KB

    Thanks for the help,but i have set the parameters right but still it does not work for me.Please suggest me reasons and how to correct them.
    Attachments:
    error.docx ‏270 KB

  • TS3899 How do I get my list of contacts from Gmail to my iPad2 so I can send email from the iPad?

    How do I get my list of contacts from Gmail to my iPad2 so I can send email from the iPad?

    Take a look at this help site that I found by using Google ...
    http://support.google.com/mobile/bin/answer.py?hl=en&answer=138740

  • After installing the new Yosemite OS on my iMac I can no longer send email. I can receive email, but not send. I use gmail and can send email on the gmail (google) site, but not on "mail" on my iMac. Any others with this problem? What should we do?

    After installing the new Yosemite OS on my iMac I can no longer send email. I can receive email, but not send. I use gmail and can send email on the gmail (google) site, but not on "mail" on my iMac. Any others with this problem? What should we do?

    My gmail, which is correctly configured for Mail with gmail SMTP and Google IMAP, works for awhile on Mail, which I leave open while working on other applications. But several times a day I get msg from Google: "We recently blocked a sign-in attempt to your Google Account" . . . and requiring me to verify my account details, re-enter passwords, confirm security settings (or change them from "disable" to "enable less secure methods" and so on). In Mail I also have tried "taking all accounts online", and re-entering my gmail password inside Mail account settings. These steps successfully re-set comms between gmail and Mail ... for awhile, then it happens again. Enough occurrences over a work day that I just quit Mail and revert to accessing gmail directly. Apple Care advisor and an Apple knowledge base article say that Apple can't deal with this, as gmail is third-party app, and they refer me to gmail, and so far I've found nothing helpful there.
    From today I also have several instances of a window saying "Mail has unexpectedly closed" and asking me to Re-open it.
    I also use Yahoo mail, which stops working with Mac Mail at the same time as gmail, but I do not receive notices to re-verify from Yahoo.
    I recently upgraded from Mavericks to Yosemite. The Mail problem happened occasionally with Mavericks but is far more frequent with Yosemite.

  • TS3276 I cannot connect to my outgoing email server on my macBook pro, yet I can, for the same email account on my iPad. Also I can send emails from the other email account I have on my MacBook...really confused can anyone help?

    I cannot connect to my outgoing email server on my macBook pro, yet I can, for the same email account on my iPad. Also I can send emails from the other email account I have on my MacBook...really confused can anyone help?

    Sometimes deleting the account and then re-creating it can solve this issue
    Write down all the information in accounts before doing this
    Highlight the account on the left and click the minus button
    Then click the plus button to add the new account and follow the prompts

  • How to get all previous versions page contents of a publishing page using SharePoint Client Object Model 2010

    How to get all previous versions page contents and other field values of a publishing page using SharePoint Client Object Model 2010?
    Thanks,
    Osmita

    Hi Osmita,
    Greetings.
    Here are the links that helps you. It has code attached to it.
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/a0d2ab40-99ba-4368-8505-1dc559ef6469/get-content-of-previous-version-of-page-sharepoint-2010?forum=sharepointgeneralprevious
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/faaf419f-997e-4150-9911-48cc375c3b46/how-to-get-previous-published-versions-of-publishing-pages-in-sharepoint-2010?forum=sharepointdevelopmentprevious
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • CAML Query to get specific item in folder based on dropdown value using Javascript client object model

    Hi,
    I am using the Javascript Client object model.
    I have a custom list and a custom document library.
    Custom list contains 2 columns - dlName , dlValue
    The document library contains 2 folders - "folder1" ,  "folder2" and contains some images.
    The image name starts with the "dlValue" available in the custom list
    I am using a visual webpart and using javascript client object model.
    I am trying to achieve the below functionality:
    1) Load a dropdown with the custom list.
    2) set the image based on the value in dropdown.
    I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
    Below is the code i have used so far:
    //In Visual webpart
    <select id="ddlTest" >
    </select>
    <br/>
    <div id="PreviewLayer">
    <img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
    </div>
    // In Javascript file
    function RenderHtmlOnSuccess() {
    var ddlTest = this.document.getElementById("ddlTest");
    ddlTest.options.length = 0;
    var enumerator = this.customListItems.getEnumerator();
    while (enumerator.moveNext()) {
    var currentItem = enumerator.get_current();
    var dropdownValue = currentItem.get_item("dlValue");
    ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
    setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
    // Also if dropdown value is changed, corresponding image should be shown
    How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
    Thanks

    Hi,
    Here are two links for your reference:
    Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
    http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
    SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
    http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
    In SharePoint 2013, we can also use REST API to achieve it.
    http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Add multiple people using Javascript Client Object Model

    I am trying to add multiple people to a SP column of type Person/Group i.e. people picker. I am able
    to add one successfully using their userId, but HAVE no clue how to do that for multiple people. Here is the code for one user:
    function UserDrop(e, toElement, listGuid, columnName) {
    //EcmaScript Client Object Model
    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getById(listGuid);
    var item = list.getItemById(elementId);
    //columnName is of type person/group and I am adding user //whose userId is 7
    item.set_item(columnName, 7);
    item.update();
    // asynchronous call
    ctx.executeQueryAsync(
    function () { toElement.innerHTML = userLinkHtml; },
    function () {alert ("Error")}
    return false;
    This works great and I can add user whose userId is 7, however I want to add multiple people like let's say users of user Ids 7 and 8. 
    Any ideas or help will be greatly appreciated. 
    There is a thread on this one but that's from .net COM which could accessed here: http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/5183e87c-ee1d-4594-9492-0dfdf6616cce
    7929

    Hi ,
    Can somebody let me know how the same(assigning the array values to lookup value field) can be achieved with multi-select lookup value. SP.FieldLookUpValue do not have any such methods like fromUser. Please help. Please find my code block below
    clientContext = new SP.ClientContext.get_current();
    if (this.clientContext != undefined && clientContext != null) {
    var webSite = clientContext.get_web();
    oList = webSite.get_lists().getByTitle("Add New User");
    $.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
    var itemid = parseInt($.urlParam('ID'));
    var item = oList.getItemById(itemid);
    var users = new Array();
    users.push(SP.FieldLookupValue.set_lookupId(1));
    users.push(SP.FieldLookupValue.set_lookupId(2));
    item.set_item('Responsibility', users);
    item.update();
    clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
    also i cant use managed client object model.. so pls let me know how to achieve the same using javascript client object model
    Ranjani.R

  • Read versions of comments field using javascript client object model

    Hi,
     Does someone knows how to Read versions  of comments field in 'tasks' list using javascript client object model?
    Thanks
    Manvir

    Hi,
    According to your description, I know you want to read versions of comments field.
    We can use the
    SPServices to achieve it. The below code for your reference:
    $().SPServices({
    operation: "GetVersionCollection",
    async: false,
    strlistID: "tester",
    strlistItemID: 1,
    strFieldName: "comments",
    completefunc: function (xData, Status) {
    $(xData.responseText).find("Version").each(function(i) {
    console.log("Name: " + $(this).attr("Information") + " Modified: " + $(this).attr("Modified"));
    More information:
    http://spservices.codeplex.com/releases/view/81401
    Best Regards,
    Dennis Guo

  • Cannot download master page using managed client object model SharePoint 2010

    string siteUrl = "http://server:port/sites/demo";
    string fileServerRelativeUrl = @"/sites/demo/_catalogs/masterpage/v4.master";
    using (ClientContext context = new ClientContext(siteUrl)){ FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileServerRelativeUrl);}
    File.OpenBinaryDirect() throws "The remote server returned an error: (404) Not Found" error. while Microsoft.SharePoint.Client.File f1 = web.GetFileByServerRelativeUrl(fileUrl);
                    context.Load(f1);
                    context.ExecuteQuery();this gives the file object.File.OpenBinaryDirect() works if I pass "/sites/demo/_catalogs/masterpage/TabViewPageLayout.aspx" as fileServerRelativeUrl.Both the files are present in Master Page Gallery.File.OpenBinaryDirect() doesn't work if I pass any of ".master" file in the master page galleryPlease let me know whether downloading the master pages is supported using managed Client object model. 

    Hi,
    If don't change the default config, We are unble to download master page.
    It's better to create your own (perhaps based on the default.master) and use that master page.
    also,make sure there's no a permission issue on the website.
    Thanks
    Guangchao chen
    TechNet Community Support

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

Maybe you are looking for

  • How do I get out of endless loop from entering improper log in information

    On a Dell laptop using Windows 7.  I logged in using a the info that came up automatically.  The system now shows a blue screen with dots going around in a circle for hours.  How can I get it to stop and log in with the correct ID?

  • Sender File Adapter pulling Incomplete File - Throwing Alert with MSecsWait

    Hi, <br>We have sender File communication channel which is polling every 600 Secs. The directory where the files are available is basically an FTP Server directory. Vendors are putting file in this directory and PI is picking up from there. <br> Some

  • Chinese Characters in Body of the Email when sending attachments.

    I have google and exchange accounts connected to mac mail. Whenever I send an attachments through the exchange account via mac mail, the recipient receives the attachment however is filled with Chinese characters in the body of the email that look li

  • Photo Folders on iPhone and iCloud

    Hello, I have my photos on my PC arranged by years in folders and sub-folders and I want to have them on my phone the exact same way AND have them saved to iCloud.  I spoke to tech support and they say this cant be done.  I would like to know if I ca

  • FORMS 6i WITH OLE ON WEB DEPLOYMENT

    We have been using forms-6i with OLE container (to use MS-Word document) under the client side deployment of the application . Now We want to use this application under the WEB (using Forms Server) , as under WEB deployment OLE is not supported , so