Abstracts an e-mail message
Example #1
0
		/// <summary>
		/// Sends multiple messages.
		/// </summary>
		/// <param name="messages">Array of messages</param>
		public void Send(Message[] messages)
		{
			foreach(Message message in messages)
			{
				context.AddEmailMessageSent(message);
			}
		}
		public virtual Message BuildMessage(IDictionary context, bool degrade)
		{
			var mail = new Message { From = From, To = To, Cc = Cc, Bcc = Bcc, Subject = Subject, Format = Format };
			AdjustMailHeaders(mail);
			mail.Body = ComposeBody(mail, context, degrade);

			return mail;
		}
		public virtual void Send(Message mail)
		{
			if (!AreValidEmailAddresses(mail.From, false))
				throw new AppException("E-mail inválido", "Endereço de e-mail inválido no campo 'De': " + mail.From);
			if (!AreValidEmailAddresses(mail.To, false))
				throw new AppException("E-mail inválido", "Endereço de e-mail inválido no campo 'Para': " + mail.To);
			if (!AreValidEmailAddresses(mail.Cc, true))
				throw new AppException("E-mail inválido", "Endereço de e-mail inválido no campo 'CC': " + mail.Cc);
			if (!AreValidEmailAddresses(mail.Bcc, true))
				throw new AppException("E-mail inválido", "Endereço de e-mail inválido no campo 'BCC': " + mail.Bcc);

			emailSender.Send(mail);
		}
		protected virtual string ComposeBody(Message msg, IDictionary context, bool degrade)
		{
			string body;
			using (var sw = new StringWriter())
			{
				templateEngine.Process(context, Template, sw);
				body = sw.ToString();
			}

			if (degrade)
				body = DegradeToHtml4(body);

			return body;
		}
		/// <summary>
		/// Aplica o XSLT de degradação para HTML 4.
		/// Importante para e-mais HTML, para poder ser lido em diversos browsers e clientes de e-mail.
		/// </summary>
		protected void DegradeToHtml4(Message mail)
		{
			if (xslHtmlEmail == null)
				throw new AppError("Arquivo Faltante", "O arquivo XSLT para degradação para HTML4 não foi encontrado.");

			// aplica o XSL de email
			using (var sr = new StringReader(mail.Body))
			using (var sw = new StringWriter())
			using (var r = XmlReader.Create(sr))
			{
				xslHtmlEmail.Transform(r, null, sw);

				sw.Flush();
				mail.Body = sw.ToString();
			}
		}
Example #6
0
        /// <summary>
        /// Verzend een email naar de ontvanger
        /// </summary>
        /// <returns>een true als er geen foutmelding was</returns>
        public void Send(string fromEmailAddress, string emailAdres, string onderwerp, string templateName, Dictionary<string, object> propertyBag, MessageAttachment[] attachments)
        {
            if (string.IsNullOrEmpty(emailAdres))
            {
                throw new Exception("Geen emailadres opgegeven");
            }
            if (string.IsNullOrEmpty(onderwerp))
            {
                throw new Exception("Geen onderwerp opgegeven");
            }

            Message message = new Message();
            message.Body = emailTemplateParserService.Parse("email", templateName, propertyBag);
            message.To = emailAdres;

            if (!string.IsNullOrEmpty(bccEmailAddress))
            {
                message.Bcc = bccEmailAddress;
            }
            if (!string.IsNullOrEmpty(fromEmailAddress))
            {
                message.From = fromEmailAddress;
            }
            else
            {
                message.From = this.fromEmailAddress;
            }
            message.Subject = onderwerp;
            message.Format = Format.Html;

            if (attachments != null)
            {
                foreach (MessageAttachment attachment in attachments)
                {
                    if (attachment != null)
                    {
                        message.Attachments.Add(attachment);
                    }
                }
            }
            Send(message);
        }
Example #7
0
		/// <summary>
		/// Attempts to deliver the Message using the server specified on the web.config.
		/// </summary>
		/// <param name="message">The instance of System.Web.Mail.MailMessage that will be sent</param>
		public void DeliverEmail(Message message)
		{
			try
			{
				IEmailSender sender = (IEmailSender) ServiceProvider.GetService( typeof(IEmailSender) );

				sender.Send(message);
			}
			catch(Exception ex)
			{
				if (logger.IsErrorEnabled)
				{
					logger.Error("Error sending e-mail", ex);
				}
				
				throw new RailsException("Error sending e-mail", ex);
			}
		}
Example #8
0
 public void Send(Message message)
 {
     try
     {
         emailSender.Send(message);
     }
     catch (Exception e)
     {
         logger.Fatal("Het versturen van de E-Mail is mislukt. ", e.Message);
         throw new Exception("Het versturen van de E-Mail is mislukt, Probeer het later nog eens.");
     }
 }
Example #9
0
		/// <summary>
		/// Sends a message.
		/// </summary>
		/// <param name="message">Message instance</param>
		public void Send(Message message)
		{
			context.AddEmailMessageSent(message);
		}
		/// <summary>
		/// Creates an instance of <see cref="Message"/>
		/// using the specified template for the body
		/// </summary>
		/// <param name="templateName">
		/// Name of the template to load. 
		/// Will look in Views/mail for that template file.
		/// </param>
		/// <param name="context">Context that represents the current request</param>
		/// <param name="controller">Controller instance</param>
		/// <param name="doNotApplyLayout">If <c>true</c>, it will skip the layout</param>
		/// <returns>An instance of <see cref="Message"/></returns>
		public Message RenderMailMessage(String templateName, IRailsEngineContext context,
		                                 Controller controller, bool doNotApplyLayout)
		{
			// create a message object
			Message message = new Message();

			// use the template engine to generate the body of the message
			StringWriter writer = new StringWriter();

			String oldLayout = controller.LayoutName;

			if (doNotApplyLayout)
			{
				controller.LayoutName = null;
			}

			if (templateName.StartsWith("/"))
			{
				controller.InPlaceRenderSharedView(writer, templateName);
			}
			else
			{
				controller.InPlaceRenderSharedView(writer, Path.Combine(Constants.EmailTemplatePath, templateName));
			}
			
			if (doNotApplyLayout)
			{
				controller.LayoutName = oldLayout;
			}

			String body = writer.ToString();
			
			// process delivery addresses from template.
			MatchCollection matches = Constants.readdress.Matches(body);

			for(int i = 0; i < matches.Count; i++)
			{
				String header = matches[i].Groups[Constants.HeaderKey].ToString().ToLower();
				String address = matches[i].Groups[Constants.ValueKey].ToString();

				switch(header)
				{
					case Constants.To :
						message.To = address;
						break;
					case Constants.Cc :
						message.Cc = address;
						break;
					case Constants.Bcc :
						message.Bcc = address;
						break;
				}
			}
			
			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Rendering email message to {0} cc {1} bcc {2}", message.To, message.Cc, message.Bcc);
			}

			body = Constants.readdress.Replace(body, String.Empty);

			// process from address from template
			Match match = Constants.refrom.Match(body);
			
			if (match.Success)
			{
				message.From = match.Groups[Constants.ValueKey].ToString();
				body = Constants.refrom.Replace(body, String.Empty);
			}

			// process subject and X headers from template
			matches = Constants.reheader.Matches(body);
			
			for(int i=0; i< matches.Count; i++)
			{
				String header = matches[i].Groups[Constants.HeaderKey].ToString();
				String strval = matches[i].Groups[Constants.ValueKey].ToString();

				if (header.ToLower(System.Globalization.CultureInfo.InvariantCulture) == Constants.Subject)
				{
					message.Subject = strval;
				}
				else
				{
					message.Headers.Add(header, strval);
				}
				
				if (logger.IsDebugEnabled)
				{
					logger.DebugFormat("Adding header {0} value {1}", header, strval);
				}
			}
			
			body = Constants.reheader.Replace(body, String.Empty);

			message.Body = body;
			
			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Email message body {0}", body);
			}

			// a little magic to see if the body is html
			if (message.Body.ToLower(System.Globalization.CultureInfo.InvariantCulture).IndexOf(Constants.HtmlTag) != -1)
			{
				message.Format = Format.Html;
				
				if (logger.IsDebugEnabled)
				{
					logger.Debug("Content set to Html");
				}
			}
			
			return message;
		}
		/// <summary>
		/// Sends multiple messages.
		/// </summary>
		/// <param name="messages">Array of messages</param>
		public void Send(Message[] messages)
		{
			sender.Send(messages);
		}
		/// <summary>
		/// Sends a message.
		/// </summary>
		/// <param name="message">Message instance</param>
		public void Send(Message message)
		{
			sender.Send(message);
		}
		private void AdjustMailHeaders(Message mail)
		{
			mail.Headers.Add("X-Suprifattus-Gen", DateTime.Now.ToString("s"));

			mail.From = RemoveAccents(mail.From);
			mail.To = RemoveAccents(mail.To);

			if (!String.IsNullOrEmpty(mail.Cc))
				mail.Cc = RemoveAccents(mail.Cc);

			if (!String.IsNullOrEmpty(mail.Bcc))
				mail.Cc = RemoveAccents(mail.Bcc);
		}
		internal void AddEmailMessageSent(Message message)
		{
			messagesSent.Add(message);
		}
Example #15
0
		private Message CreateMessage(StringWriter writer)
		{
			// create a message object
			Message message = new Message();

			StringReader reader = new StringReader(writer.ToString());

			bool isInBody = false;
			StringBuilder body = new StringBuilder();
			string line;

			while((line = reader.ReadLine()) != null)
			{
				string header, value;
				if (!isInBody && IsLineAHeader(line, out header, out value))
				{
					switch(header.ToLowerInvariant())
					{
						case "to":
							message.To = value;
							break;
						case "cc":
							message.Cc = value;
							break;
						case "bcc":
							message.Bcc = value;
							break;
						case "subject":
							message.Subject = value;
							break;
						case "from":
							message.From = value;
							break;
						default:
							message.Headers[header] = value;
							break;
					}
				}
				else
				{
					isInBody = true;

					if (line == string.Empty)
					{
						continue;
					}

					body.AppendLine(line);
				}
			}

			message.Body = body.ToString();

			if (message.Body.ToLowerInvariant().IndexOf("<html>") != -1)
			{
				message.Format = Format.Html;
			}

			return message;
		}