So you want to send an email..... - Hilary Stoupa
in

InfoPath Dev

Hilary Stoupa

So you want to send an email.....

There are two very common email scenarios with InfoPath. One -- you want to use an email submit connection but modify some things before the email goes out (common reasons: you'd like to use form fields in the Information section which is not currently supported in the user interface, you need more flexibility to determine who the email should be sent to, you have other logic you need to perform prior to sending the form) and two -- you don't want to submit the form via email, you just need to send an email to someone with some form information in it.

Let's address both of those scenarios. A few caveats first --for scenario 1, I haven't included error handling. If your user cancels the submit when they see the preview of the email to be submitted, they are going to get some ugly messages. I'm sorry. It is Sunday afternoon, and I'm being a slacker. Also, for scenario 2,  your form will have to be full trust to do cool stuff like send an email that isn't based on a submit connection -- at least, mine had to be. 

Here is the data source I'll be using for all the samples, just so you know what the xpath is pointing to:
Data Source

Okay, without further ado, scenario 1:

Modify email submit properties before submitting:

In this scenario, I have added an email submit connection to my form. My form submit options are set to use my email connection:

Submit Options dialog

Also, I've added a button to my form that I'm *calling* a submit button, but in reality, it is just an ordinary old button I've labeled Submit:

Button Properties

C# -- 2007 Object Model

        public void btnSubmit_Clicked(object sender, ClickedEventArgs e)
        {
            //get the value from the text field
            string interestingText = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:textField", NamespaceManager).Value;
            //get the value from the date field
            string date = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:dateField", NamespaceManager).Value;
 
            //get that email submit connection
            EmailSubmitConnection emailSubmit = (EmailSubmitConnection)this.DataConnections["Email Submit"];
 
            //set the introduction with a value from the form
            emailSubmit.Introduction = "This is my shiny new introduction with a date from my form: " + date + "\nAnd an interesting value from a text field as well: " + interestingText;
 
            //submit the form
            this.Submit();
        }

VB.Net -- 2007 Object Model

        Public Sub btnSubmit_Clicked(ByVal sender As Object, ByVal e As ClickedEventArgs)
            'get the value from the text field
            Dim interestingText As String = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:textField", NamespaceManager).Value
            'get the value from the date field
            Dim dateField As String = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:dateField", NamespaceManager).Value
 
            'get that email submit connection
            Dim emailSubmit As EmailSubmitConnection = Me.DataConnections("Email Submit")
 
            'set the introduction with a value from the form
            emailSubmit.Introduction = "This is my shiny new introduction with a date from my form: " + dateField + System.Environment.NewLine + "And an interesting value from a text field as well: " + interestingText
 
            'submit the form
            Me.Submit()
        End Sub

And, scenario 2:

Send an email with some form information in it:

We are going to use a button click event (I named my button btnEmail -- nothing against the oh-so-intuitive IP default names like 'CTRL15_23' but I am fond of slightly more meaningful names) and send an email to someone with information from the textField and the dateField in our form.

C# -- 2007 Object Model

        public void btnEmail_Clicked(object sender, ClickedEventArgs e)

        {

            //get the value from the text field

            string subject = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:textField", NamespaceManager).Value;

            //get the value from the date field

            string date = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:dateField", NamespaceManager).Value;

           

            //set the information for the message

            MailAddress from = new MailAddress("[email protected]");

            MailAddress to = new MailAddress("[email protected]");

            MailMessage msgmail = new MailMessage(from, to);

 

            //the body has the date variable we created in it, the subject uses the value from our text box -- mind you, this is all made up for a demo, so it isn't all that interesting

            msgmail.Body = "A new form was created on " + date + ". Please review it.";

            msgmail.Subject = subject;

 

            //this stuff is going to vary depending on your setup

            SmtpClient client = new SmtpClient("smtp.someServer.com");

            client.Credentials = new System.Net.NetworkCredential("someUserName", "somePassword");

 

            //send that baby out

            client.Send(msgmail);

        }

At the top of your code window, with the other "using" statements, be sure to add this:

using System.Net.Mail;

VB.Net -- 2007 Object Model

        Public Sub btnEmail_Clicked(ByVal sender As Object, ByVal e As ClickedEventArgs)
            'get the value from the text field
            Dim subject As String = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:textField", NamespaceManager).Value
            'get the value from the date field
            Dim dateField as String = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:dateField", NamespaceManager).Value
 
            'set the information for the message
            Dim fromAddress As MailAddress = New MailAddress("[email protected]")
            Dim toAddress As MailAddress = New MailAddress("[email protected]")
            Dim msgmail As MailMessage = New MailMessage(fromAddress, toAddress)
 
            'the body has the date variable we created in it, the subject uses the value from our text box -- mind you, this is all made up for a demo, so it isn't all that interesting
            msgmail.Body = "A new form was created on " + dateField + ". Please review it."
            msgmail.Subject = subject
 
            'this stuff is going to vary depending on your setup
            Dim client As SmtpClient = New SmtpClient("smtp.someServer.com")
            client.Credentials = New System.Net.NetworkCredential("someUserName", "somePassword")
 
            'send that baby out
            client.Send(msgmail)
        End Sub

At the top of your code window, with the other "Imports" statements, be sure to add this:

Imports System.Net.Mail

Now promise to only use your newfound powers for good, and have fun!

Comments

 

Developer said:

Hi Hilary,

Thank you for your truly enlightening post. I have tried the steps above and it works for me. There is one bit I would like you to help with.

My form has got a Submit button which sends email when clicked. The issue is that email is sent even if the form has not been submitted successfully; for example if all mandatory fields have not been filled. Which event does the email code above need to be moved to so that when the button is clicked, email is sent only if the form has been fully validated (with no errors)?

Many thanks.

October 26, 2008 6:24 PM
 

Hilary Stoupa said:

Hi -- Sorry I was slow to notice this. You could add the code to your Submit Request event, I suppose. You can check the Errors.Count to see if there are validation errors before sending the email.

November 11, 2008 8:31 AM
 

akankshas said:

I created a InfoPath which sends out an email and would like to have “Send” button with default index so that the forms gets submitted successfully.

Could you please guide me or direct me to the resource or KB which details on how to adjust the default index on email message popup in InfoPath form.

December 11, 2008 5:32 AM
 

Hilary Stoupa said:

I'm sorry -- I don't understand the question. Can you explain in more detail what you need to do?

December 30, 2008 8:09 AM
 

bbfbowler said:

Hi, nice code, I have a question.  I would like just not to send an email, but to send the form as the attachment as well, without the user saving the form. Is there a way this can be done?

Thanks in advance!!!

March 11, 2009 9:28 AM
 

Hilary Stoupa said:

There is some great info here: www.systemnetmail.com/.../2.3.aspx

It says that System.Net.Mail can create an attachment from a stream... I'm afraid I've never tried it though. If you do, and have success, perhaps you'd share your code?

March 13, 2009 5:33 PM
 

hgedixon said:

Nice posting. This may be a little off the tangent...Let say that you are publishing a form using email recipients, is there a way to write code for when the "Send" button is pressed? I want to create a task for each recipient of the email in a SharePoint Task list but only after the email has went out.

March 26, 2009 6:26 AM
 

rjwmets said:

Is there any way to use the above C# code, but for the "body" field, send the current view of the form? I've been searching for code to do this, but I have not been able to find anything

June 30, 2009 7:58 AM
 

Hilary Stoupa said:

hgedixon: I don't know how to hook the Outlook event (pressing send) from w/in the InfoPath code.

rjwmets: You can always recreate the view, I think there have been some posts, but it is a bit laborious. I take it you aren't using IP 2007?

September 27, 2009 6:35 AM
 

alexd said:

Thank you! Worked perfectly and saved me a headache or two.

September 29, 2009 9:28 AM
 

ncolyer said:

Hilary,

I'm trying to do something similar to what you have described here.

Essentially I want to add various fields to the body of my message.

What I want to happen now is to have a submit button that doesn't send all the date but just certain fields in the body of the message and doesn't send the attachment.

When I click "Edit Form Code" I get the Microsoft Script Editor but it is called script.js - is this JavaScript? Can I use the same code or similar code to what you have above or do I have to find another way?

Thanks,

Nick

April 19, 2010 2:52 PM
 

Hilary Stoupa said:

Hey, Nick --

Sounds like you are using IP 2003. These code samples are for C# or VB.NET. Do you have access to Visual Studio? You can add managed code to an InfoPath 2003 template in Visual Studio. Or, if you are using IP 2007, you can use VSTA.

May 26, 2010 4:48 PM
 

Infopath Email « Sladescross's Blog said:

Pingback from  Infopath Email « Sladescross's Blog

January 23, 2011 10:46 AM
 

Infopath Email « Sladescross's Blog said:

Pingback from  Infopath Email « Sladescross's Blog

January 23, 2011 10:46 AM
 

DXXPublic said:

Hi Hilary,

After days and days of  looking for a solution i bumped into this WONDERFUL link and 90% of my issues dissapeared  :) ... Everything is working great, BUT since im using a repeatable Table it always uses the information of the 1st table.  Would you help me with this please?

February 4, 2011 3:43 AM
 

Hilary Stoupa said:

You are going to need an XPathNodeIterator. Take a quick peek at the MSDN docs on that, or search this forum, and you should find some help....

February 10, 2011 11:28 AM
 

sudheshdessai said:

Hi Hilary

I am getting an error at the object smtpclient object creation with no parameter.

Dim smtpClient as SmtpClient = new SmtpClient()

Below is the error:

System.Security.SecurityException was unhandled by user code

 GrantedSet="<PermissionSet class="System.Security.PermissionSet" version="1"> <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="USERNAME"/> <IPermission class="System.Security.Permissions.FileDialogPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="\\xx.xxx.NET\USERS\xxxxx\Visual Studio 2008\Projects\InfoPathFormTemplate1\InfoPathFormTemplate1\InfoPath Form Template\" PathDiscovery="\\xxx.xxx.NET\USERS\xxx\Visual Studio 2008\Projects\InfoPathFormTemplate1\InfoPathFormTemplate1\InfoPath Form Template\"/> <IPermission class="System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Allowed="AssemblyIsolationByUser" UserQuota="9223372036854775807" Expiry="9223372036854775807" Permanent="True"/> <IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ReflectionEmit"/> <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Assertion, Execution, BindingRedirects"/> <IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> <IPermission class="System.Security.Permissions.UrlIdentityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Url="file:///\\xxxxFS01.xxx.net\users\xxxx\Visual%20Studio%202008\Projects\InfoPathFormTemplate1\InfoPathFormTemplate1\InfoPath%20Form%20Template\manifest.xsf"/> <IPermission class="System.Security.Permissions.ZoneIdentityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Zone="Intranet"/> <IPermission class="System.Net.DnsPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> <IPermission class="System.Drawing.Printing.PrintingPermission, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" version="1" Level="DefaultPrinting"/> <IPermission class="Microsoft.Office.InfoPath.InfoPathPermission, Microsoft.Office.InfoPath.Client.Internal.Host, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1" Unrestricted="true"/> </PermissionSet> "

 Message="Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."

 PermissionState="<IPermission class="System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Access="Connect"/> "

 RefusedSet=""

 Source="mscorlib"

 Url="file:///C:/Documents and Settings/suddes/Local Settings/Application Data/Microsoft/InfoPath/FormCache2/FFF9F835.D5C/cf2c34269087d44d$7695a4fd7ac888c1/InfoPathFormTemplate1.DLL"

 StackTrace:

      at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)    at System.Security.CodeAccessPermission.Demand()    at System.Net.Mail.SmtpClient.Initialize()    at System.Net.Mail.SmtpClient..ctor()    at InfoPathFormTemplate1.FormCode.Submit_Clicked(Object sender, ClickedEventArgs e)    at Microsoft.Office.InfoPath.Internal.ButtonEventHost.OnButtonClick(DocActionEvent pEvent)    at Microsoft.Office.Interop.InfoPath.SemiTrust._ButtonEventSink_SinkHelper.OnClick(DocActionEvent pEvent)

 InnerException:

March 14, 2011 2:09 AM
 

Submit Email | AllGraphicsOnline.com said:

Pingback from  Submit Email | AllGraphicsOnline.com

April 2, 2011 8:27 PM
 

Hilary Stoupa said:

Hey, sudheshdessai:

You need to change the trust level of your form.

April 4, 2011 11:39 AM
 

Sam R said:

In scenario 2, is there a way code for the From: email field to pull from an email address entered in the InfoPath form or to use Outlook email address of the person completing the form?

If not, are there any other coding options that would enable users to save the completed InfoPath form to a shared drive and then email a link with the address to the completed form to a set email address?

The issue we're having is we cannot email the InfoPath form as an attachment because it is getting embedded in the email by Outlook 2007 and then the form can't be displayed by application receiving the email.

Thanks for your excellent tutotial!

September 1, 2011 10:07 AM
 

Hilary Stoupa said:

Hi, Sam - I am really bad about checking my blog posts for comments, sorry about that.

The code sample does include getting the "from" address - you just need to get the value from your field - something like:

this.MainDataSource.CreateNavigator().SelectSingleNode("yourXPath", NamespaceManager).Value

December 30, 2011 4:13 PM
 

MDSenoj said:

Hi Hilary, I'm trying to use this code in IR 2010 with VSTA and would like to use Exchange and Outlook email instead of SMTP.

Can you show me how it would be done in that situation?

Thanks!

February 3, 2013 2:49 PM
 

MDSenoj said:

*forgot to mention I'm trying to accomplish Scenario 2 - I just want to send the email from Outlook using some of the data from the form.  

AND, as if things aren't complex enough, I would like to send the email 7 days after the date the form is completed.

February 3, 2013 2:52 PM
 

Hilary Stoupa said:

I'm not at all sure how you'd go about sending the email 7 days after the form is completed. I wonder if there might be a way using SharePoint Workflow?

March 4, 2013 5:39 PM
 

ShahC said:

Hi Hilary,

Is it possible to send a section of the infopath form (as is) and not just the data values using SMTP?

November 10, 2014 7:53 PM

About Hilary Stoupa

I wandered into development after working as a business process analyst for a global manufacturing company. I create InfoPath solutions for our clients as well as work as a developer on company tools that extend InfoPath. I've also been instrumental in creating the InfoPath Master Class training provided by Qdabra.

Copyright © 2003-2019 Qdabra Software. All rights reserved.
View our Terms of Use.