Quantcast
Channel: SharePoint 2010 - Development and Programming forum
Viewing all articles
Browse latest Browse all 11571

SharePoint 2010 : send confirmation email

$
0
0

I started programming in C # and ASP and i'm having trouble setting up a shipping confirmation by email after the user fills out a form system.
I'm on SharePoint (Extranet), and I have a form to register for training.
Everything is in place and I managed to send the mail to the relevant department by taking the fields filled by the user.
I would however, the user can receive an email confirmation.

I would like to retrieve the fields "email" that the user has specified for sent a confirmation email.

Currently I have my code to send mail to the appropriate department :

namespace WCFSharePoint
{
    [ServiceContract]
    public interface Testservice
    {        
        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string registertraining(string url, string firstname, string lastname, string email, string company, string job, string address1, string address2, string trainingname, string trainingdate, string message, string captchachallenge, string captcharesponse);

    }

    [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
    [AspNetCompatibilityRequirementsAttribute(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class testservice : Testservice
    {
        #region service methods

public string registertraining(string url, string firstname, string lastname, string email, string company, string job, string address1, string address2, string trainingname, string trainingdate, string message, string captchachallenge, string captcharesponse)
        {
            string mailTraining = null;
            try
            {
                mailTraining = ConfigurationManager.AppSettings[Constants.APPSETTINGSKEY_MAILTRAINING];
            }
            catch { }

            if (string.IsNullOrEmpty(mailTraining))
            {
                // -- Use default email set in SharePoint
                mailTraining = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
            }

            try
            {
                //Check captcha validation
                string response = VerifyCaptcha(captchachallenge, captcharesponse);
                if (response.ToLowerInvariant().StartsWith("true"))
                {
                    SendEmail(mailTraining, string.Format("Registering for training: {0} (Date: {1})", trainingname, trainingdate), BuildRegisterTrainingBody(firstname, lastname, email, company, job, address1, address2, message), null);
                    return "Your request has been sent.";
                }
                else
                {
                    return "The captcha verification didn't work. Please try again.";
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(Logger.CATEGORY_WEBSERVICE, string.Format(@"An unexpected error has occurred in the RegisterTraining method ({0}))", ex.Message), ex);
                throw;
            }
        }

       #endregion

       #region private methods

        private void SendEmail(string mailTo, string subject, string body, List<FileMetadata> attachments)
        {
            FileStream[] files = null;
            try
            {
                //Get the Sharepoint SMTP information from the current farm
                string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
                string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

                //Create the mail message and supply it with from and to info
                System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(smtpFrom, mailTo, subject, body);

                if (attachments != null)
                {
                    files = new FileStream[attachments.Count];
                    int i = 0;
                    foreach (FileMetadata attachment in attachments)
                    {
                        files[i] = new FileStream(attachment.FullPath, FileMode.Open, FileAccess.Read);
                        mailMessage.Attachments.Add(new Attachment(files[i], attachment.FileName));
                        i++;
                    }
                }

                //Create the SMTP client object and send the message
                SmtpClient smtpClient = new SmtpClient(smtpServer);
                smtpClient.Send(mailMessage);

                Logger.LogVerbose(Logger.CATEGORY_WEBSERVICE, string.Format("Mail sent: mailto: {0}, subject: {1}", mailTo, subject));
            }
            finally
            {
                if (files != null)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        files[i].Close();
                        files[i].Dispose();
                    }
                }
            }
        }

        private string BuildRegisterTrainingBody(string firstname, string lastname, string email, string company, string job, string address1, string address2, string message)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Register for training");
            sb.AppendLine();
            sb.AppendLine(string.Format("From : {0} ({1} {2})", email, firstname, lastname));
            sb.AppendLine(string.Format("Company : {0} / Job : {1}", company, job));
            sb.AppendLine();
            sb.AppendLine(string.Format("Billing address :"));
            sb.AppendLine(string.Format("{0}", address1));
            sb.AppendLine(string.Format("{0}", address2));
            sb.AppendLine();
            sb.AppendLine("Message :");
            sb.AppendLine(message);

            return sb.ToString();
        }
        #endregion
    }
}

My JS to get my json parameters :

	function registerTraining() {
		if( validateEmail($("#inputEmail").val()) == false)
		{
			alert('Invalid e-mail address.');
			return;
		}
		var path = $(location).attr('href');

		var capchallenge = Recaptcha.get_challenge();
		var capresponse = Recaptcha.get_response();
		try {
			var parameters = '{ "url" : "' + cleanJSONString(path) + 
							'", "firstname" : "' + cleanJSONString($("#inputFirstname").val()) + 
							'", "lastname" : "' + cleanJSONString($("#inputLastname").val()) + 
							'", "email" : "' + cleanJSONString($("#inputEmail").val()) + 
							'", "company" : "' + cleanJSONString($("#inputCompany").val()) + 
							'", "job" : "' + cleanJSONString($("#inputJob").val()) + 
							'", "address1" : "' + cleanJSONString($("#inputBillingAddress1").val()) + 
							'", "address2" : "' + cleanJSONString($("#inputBillingAddress2").val()) + 
							'", "trainingname" : "' + cleanJSONString(GetQueryStringParams("n")) +
							'", "trainingdate" : "' + cleanJSONString(GetQueryStringParams("d")) +
							'", "message" : "' + cleanJSONString($("#inputMessage").val()) + 
							'", "captchachallenge" : "' + capchallenge + 
							'", "captcharesponse" : "' + capresponse  + '" }';
			$.ajax({
				type: "POST",
				url: '_vti_bin/json/testservice.svc/registertraining',
				contentType: "application/json; charset=utf-8",
				dataType: 'json',
				data: parameters,
				success: function (msg) {
					registerTrainingSucceeded(msg);
				},
				error: registerTrainingFailed
			});
		}
		catch (e) {
			alert('Error invoking service' + e);
		}
		Recaptcha.reload();
	}
	function registerTrainingSucceeded(result) {
		alert(result.registertrainingResult);
	}
	function registerTrainingFailed(error) {
		alert('An error occured on the server.');
	}

Now I would like to perfect thing by sending the confirmation email to the person who completed the form.

Could you help me please ??

Best regards,


Viewing all articles
Browse latest Browse all 11571

Trending Articles