public void OnSendError(IMailMessage mailMessage) { var entity = (QueuedEmail)mailMessage; entity.SentTries++; Update(entity); }
public MailMessageSenderResult Send(IMailMessage msg) { int ErrorCount = 0; for (; ;) { try { return(Transmit(msg)); } catch (Exception e) { if (!EnableRetryOnError) { throw; } ErrorCount++; if (ErrorCount < RetryOnErrorCount) { Thread.Sleep(1000); } else { throw new InvalidOperationException("Send failed after " + RetryOnErrorCount + " retries. " + e.Message, e); } } } }
static void Main(string[] args) { POPClient client = new POPClient(); client.Server = "127.0.0.1"; client.Port = 110; client.Password = "******"; client.User = "******"; client.CommandIssued += new CommandIssuedEventHandler(client_CommandIssued); int count = client.CountMessage(); for (int i = 0; i <= count; i++) { IMailMessage m = client.FetchMail(i); string name = System.Guid.NewGuid().ToString() + ".msg"; System.IO.File.WriteAllText(name, m.Source); System.Console.WriteLine(m.Subject + "\r->\r" + name); } System.Console.ReadLine(); }
public static void AddMessage( IMailMessage message ) { if ( World.Saving ) _addQueue.Enqueue( message ); else m_MailMessages[message.Serial] = message; }
public EmailManagerQueue(IMailMessage mailMessage) { _mailMessage = mailMessage; var account = CloudStorageAccount.DevelopmentStorageAccount; _queueClient = account.CreateCloudQueueClient(); }
protected virtual StorableMailMessage CopyToStorableMailMessage(IMailMessage other) { var storeMessage = new StorableMailMessage { CreationDate = DateTime.Now, NextRetryDate = DateTime.Now, From = other.From, To = other.To, Cc = other.Cc, Bcc = other.Bcc, Body = other.Body, IsHtmlBody = other.IsHtmlBody, ReplyTo = other.ReplyTo, Subject = other.Subject }; foreach (var att in other.Attachments) { using (var memoryStream = new MemoryStream()) { att.GetContentStream().CopyTo(memoryStream); storeMessage.Add(new StorableMailAttachment(storeMessage) { ContentType = att.GetContentType(), Content = memoryStream.ToArray() }); } } return(storeMessage); }
public async Task ProcessMessagesAsync(CancellationToken token) { CloudQueue queue = _queueClient.GetQueueReference(mailQueueName); await queue.CreateIfNotExistsAsync(); while (!token.IsCancellationRequested) { // The default timeout is 90 seconds, so we won’t continuously poll the queue if there are no messages. // Pass in a cancellation token, because the operation can be long-running. CloudQueueMessage message = await queue.GetMessageAsync(token); if (message != null) { IMailMessage mailMessage = JsonConvert.DeserializeObject <MailMessage>(message.AsString); string apiKey = "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"; dynamic sg = new SendGridAPIClient(apiKey); Email from = new Email(mailMessage.From); string subject = mailMessage.Subject; Email to = new Email(mailMessage.To); Content content = new Content("text/html", mailMessage.Body); Mail mail = new Mail(from, subject, to, content); //mail.TemplateId = "451f5afd-498d-4117-af97-e815cdb98560"; //mail.Personalization[0].AddSubstitution("-name", model.Name); //mail.Personalization[0].AddSubstitution("-pwd-", model.Password); dynamic response = await sg.client.mail.send.post(requestBody : mail.Get()); queue.DeleteMessage(message); } } }
public MailMessageSenderResult Send(IMailMessage msg) { List <MessageType> DistinctSenders = new List <MessageType>(); foreach (IMessageRecipient recipient in msg.Recipients) { if (!DistinctSenders.Contains(recipient.MessageType)) { DistinctSenders.Add(recipient.MessageType); } } MailMessageSenderResult result = new MailMessageSenderResult(); foreach (MessageType messageType in DistinctSenders) { // Create new message with only one type of recipients MailMessage FilteredMsg = new MailMessage(); FilteredMsg.Recipients.AddRange(msg.Recipients[messageType]); FilteredMsg.Sender = msg.Sender; FilteredMsg.Attachments.AddRange(msg.Attachments); FilteredMsg.Body.AddRange(msg.Body); FilteredMsg.IsBulk = msg.IsBulk; FilteredMsg.Subject = msg.Subject; MailMessageSenderResult senderResult = Transmit(messageType, FilteredMsg); result.RecipientResults.AddRange(senderResult.RecipientResults); } return(result); }
private static MailData ConvertMailMessage( IMailMessage message ) { Type messageType = message.GetType(); MailTemplateAttribute mailTemplateAttribute = (MailTemplateAttribute)Attribute.GetCustomAttribute( messageType, typeof( MailTemplateAttribute ) ); using( MemoryStream resStream = new MemoryStream() ) { using( MemoryStream srcStream = new MemoryStream() ) { XmlSerializer xs1 = new XmlSerializer( messageType ); xs1.Serialize( srcStream, message ); srcStream.Seek( 0, SeekOrigin.Begin ); using( XmlTextReader rd = new XmlTextReader( srcStream ) ) { mailTemplateAttribute.XslTransform.Transform( rd, null, resStream ); } } resStream.Seek( 0, SeekOrigin.Begin ); XmlDocument doc = new XmlDocument(); doc.Load( resStream ); MailData res = new MailData(); res.Body = doc.DocumentElement.OuterXml; XmlNode node = doc.SelectSingleNode( "/html/head/title" ); if( node == null || string.IsNullOrEmpty( node.InnerText ) ) throw new Exception( "message title is empty" ); res.Subject = node.InnerText; return res; } }
public Task SaveMessageAsync(IMailMessage messageHeader) { return(Task.Factory.StartNew(() => { SaveMessage(messageHeader, messageHeader); })); }
public void OnSendSuccess(IMailMessage mailMessage) { var entity = (QueuedEmail)mailMessage; entity.SentOnUtc = DateTime.UtcNow; Update(entity); }
protected void ReadBody(ref Stream dataStream, ref IMailMessage message) { var result = new DataReader(m_EndOfMessageCriteria).ReadData(ref dataStream); string body = new string(result.Data); m_Source.Append(body); message.TextMessage = body; }
public void SendMessage(IMailMessage msg) { using var smtpclient = _settings.SmtpPort > 0 ? new SmtpClient(_settings.SmtpHost, _settings.SmtpPort) : new SmtpClient(_settings.SmtpHost); smtpclient.Send((MailMessage)msg); }
void callbackmethod(IAsyncResult result) { IMailMessage message = client.EndFetchMail(result); jingxian.mail.mime.RFC2045.IMimeMailMessage mimeMessage = message as jingxian.mail.mime.RFC2045.IMimeMailMessage; SetValue(0); ShowMesage(mimeMessage); }
private void VerifyMimiType(IMailMessage messagesSent) { var msgId = ((MailMessage)messagesSent).Id; _client.GetMessage(msgId).Payload.Parts.Should() .ContainSingle(x => x.MimeType == MediaTypeNames.Text.Plain).And .ContainSingle(x => x.MimeType == MediaTypeNames.Text.Html); }
private MailMessage BuildMailMessage(IMailMessage message, object messageModel = null) { dynamic builder = GetMailBuilder(message); var builtMessage = builder.Build((dynamic)message, (dynamic)messageModel); return(builtMessage); }
public async void Send <TModel>(IMailMessage <TModel> message) { var builtMessage = BuildMailMessage(message, message.Model); await MailSender.SendMailAsync(builtMessage).ConfigureAwait(true); // SaveMessageLogItem(builtMessage as MailMessage); }
public async void Send(IMailMessage message) { var builtMessage = BuildMailMessage(message: message); // SaveMessageLogItem(builtMessage as MailMessage); // todo: re-design mail message components to store log items correctly await MailSender.SendMailAsync(builtMessage).ConfigureAwait(true); }
public void Send(IMailMessage message) { if (message == null) { throw new InvalidMailMessage("Mail Message is required"); } if (!enabled) { //log.Warn("Sending e-mail is disabled. Ignoring message"); return; } // log.Debug("Sending e-mail..."); MailMessage mail; try { mail = BuildMailMessage(message); } catch (Exception e) { // log.Error("Mailer Message contains some invalid information and cannot be sent", e); throw new InvalidMailMessage(e); } try { smtp.Send(mail); // log.Debug("e-mail sent successfully!"); } catch (SmtpException e) { // log.Error("Error sending e-mail", e); if (e.Message.Contains("timed out")) { throw new TimeoutTransportMailException(e); } if (e.StatusCode == SmtpStatusCode.MustIssueStartTlsFirst) { throw new AuthenticationRequiredMailMessage(e); } if (e.StatusCode == SmtpStatusCode.GeneralFailure) { throw new TransportMailMessageException(e); } else { throw new TransportMailMessageException(e); } } catch (Exception e) { //log.Error("Error sending e-mail", e); throw new InvalidMailMessage(e); } }
private static void Enqueue(MessageType messageType, IMailMessage msg) { MessageContainer c = new MessageContainer(); c.msg = msg; c.SendTime = DateTime.Now; c.msgType = messageType; Enqueue(c); }
/// <summary> /// process an email and call processAttachement for every attachement /// which fires an event for every new attachement /// </summary> /// <param name="m"></param> /// <returns></returns> public int processMail(IMailMessage m)// (Microsoft.Exchange.WebServices.Data.EmailMessage m) { int iRet = 0; if (m == null) { utils.helpers.addLog("processMail: null msg"); OnStateChanged(new StatusEventArgs(StatusType.error, "NULL msg")); return(iRet); } try { OnStateChanged(new StatusEventArgs(StatusType.none, "processing " + m.Attachements.Length.ToString() + " attachements")); utils.helpers.addLog(m.User + "," + m.Subject + ", # attachements: " + m.Attachements.Length.ToString() + "\r\n"); //get data from email string sReceivededBy = m.User; DateTime dtSendAt = m.timestamp; //get data from body LicenseMailBodyData bodyData = new LicenseMailBodyData(); OnStateChanged(new StatusEventArgs(StatusType.none, "processing mail body")); utils.helpers.addLog("processing mail body"); bodyData = processMailBody(m); utils.helpers.addLog("mail body='" + m.Body + "'"); utils.helpers.addLog(bodyData.dump()); if (m.Attachements.Length > 0) { //process each attachement foreach (Attachement a in m.Attachements) { try { utils.helpers.addLog("start processAttachement...\r\n"); iRet += processAttachement(a, bodyData, m); OnStateChanged(new StatusEventArgs(StatusType.none, "processed " + iRet.ToString() + " licenses")); utils.helpers.addLog("processAttachement done\r\n"); } catch (Exception ex) { utils.helpers.addExceptionLog(ex.Message); OnStateChanged(new StatusEventArgs(StatusType.error, "Exception1 in processAttachement: " + ex.Message)); } } } } catch (Exception ex) { utils.helpers.addLog("Exception: " + ex.Message); OnStateChanged(new StatusEventArgs(StatusType.error, "Exception2 in processAttachement: " + ex.Message)); } utils.helpers.addLog("processMail did process " + iRet.ToString() + " files"); return(iRet); }
public void Delete(IMailMessage message) { if (!(message is MailMessage mailMessage)) { throw new InvalidCastException( $"Unable to delete message of type '{message.GetType().FullName}'. Expected type '{message.GetType().FullName}'"); } Delete(mailMessage.Id); }
public QueueMessage(IMailMessage other) { var now = DateTime.Now; this.wrapped = other; this.Id = now.Ticks; this.CreationDate = now; this.NextRetryDate = now; this.Retries = 0; }
public void Send(IMailMessage message) { var hostSettings = hostSettingsProvider.GetSettings(); var credentials = new NetworkCredential(hostSettings.Username, hostSettings.Password); SMTP instance = SMTP.GetInstance(credentials, hostSettings.Host, hostSettings.Port); // don't like this, but will do for now var sendGridMessageWrapper = (SendGridMessageWrapper)message; instance.Deliver(sendGridMessageWrapper.SendGrid); }
public void SendMail(IMailMessage mailMessage) { var app = new Application(); var mail = app.CreateItem(OlItemType.olMailItem); mail.Body = mailMessage.Body; mail.Recipients.Add("*****@*****.**"); mail.Recipients.Add("*****@*****.**"); mailMessage.AttachmentPaths.ForEach(x => mail.Attachments.Add(x)); mail.Subject = mailMessage.Subject; mail.Send(); }
public static void AddMessage(IMailMessage message) { if (World.Saving) { _addQueue.Enqueue(message); } else { m_MailMessages[message.Serial] = message; } }
public static LicenseMailBodyData get(IMailMessage msg) { LicenseMailBodyData data = new LicenseMailBodyData(); string sBody = msg.Body; sBody = sBody.Replace("\r\n", ";"); var expression = new Regex( @"Order Number:[ ]+(?<order_number>[\S]+);" + @".+Order Date:[ ]+(?<order_date>[\S]+);" + @".+Your PO Number:[ ]+(?<po_number>[\S]+);" + @".+End Customer:[ ]+(?<end_customer>[\S]+);" + "" ); string currentMatch = "START"; string gMatch = ""; try { var match = expression.Match(sBody); currentMatch = "order_number"; //utils.helpers.addLog(string.Format("order_number......{0}", match.Groups["order_number"])); data.OrderNumber = match.Groups["order_number"].Value; currentMatch = "order_date"; //utils.helpers.addLog(string.Format("order_date........{0}", match.Groups["order_date"])); gMatch = match.Groups["order_date"].Value.TrimEnd(new char[] { ';' }); data.OrderDate = getDateTimeFromUSdateString(gMatch); currentMatch = "po_number"; //utils.helpers.addLog(string.Format("po_number........ {0}", match.Groups["po_number"])); data.yourPOnumber = match.Groups["po_number"].Value; currentMatch = "end_customer"; //utils.helpers.addLog(string.Format("end_customer..... {0}", match.Groups["end_customer"])); data.EndCustomer = match.Groups["end_customer"].Value; currentMatch = "Product"; expression = new Regex(@".+Product:[ ]+(?<product>.+);.+Quantity"); match = expression.Match(sBody); //utils.helpers.addLog(string.Format("product...........{0}", match.Groups["product"])); data.Product = match.Groups["product"].Value; currentMatch = "Quantity"; expression = new Regex(@".+Quantity:[ ]+(?<quantity>[0-9]+);"); match = expression.Match(sBody); //utils.helpers.addLog(string.Format("quantity..........{0}", match.Groups["quantity"])); data.Quantity = Convert.ToInt16(match.Groups["quantity"].Value.TrimEnd(new char[] { ';' })); } catch (Exception ex) { utils.helpers.addLog("Exception processing mail body regex: " + ex.Message + "\r\ncurrent expression: " + expression + "\r\ncurrentMatch: " + currentMatch); throw new FormatException("RegEx fails for MailBody"); } return(data); }
public void EnqueueMail(IMailMessage msg) { if (_stopped) { return; } _mainQueue.Enqueue(new QueuedMail { Msg = msg }); startSending(); }
private MailMessage BuildMailMessage(IMailMessage msg) { var from = msg.From; var to = msg.To; var subject = msg.Subject; var body = msg.Body; var mail = new MailMessage(from, to, subject, body); mail.IsBodyHtml = msg.IsHtmlBody; if (!string.IsNullOrWhiteSpace(msg.ReplyTo)) { mail.ReplyToList.Add(new MailAddress(msg.ReplyTo)); } if (!string.IsNullOrWhiteSpace(msg.Cc)) { mail.CC.Add(msg.Cc); } if (!string.IsNullOrWhiteSpace(msg.Bcc)) { mail.Bcc.Add(msg.Bcc); } if (mail.IsBodyHtml) { mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html"))); } if (msg.Attachments != null && msg.Attachments.Count > 0) { foreach (var attachment in msg.Attachments) { var stream = attachment.GetContentStream() as MemoryStream; if (stream == null) { var att = new Attachment(attachment.GetContentStream(), new ContentType(attachment.GetContentType())); mail.Attachments.Add(att); } else { var mem = new MemoryStream(stream.ToArray()); var att = new Attachment(mem, new ContentType(attachment.GetContentType())); mail.Attachments.Add(att); } } } return(mail); }
private static byte GetMailMessageIndex( IMailMessage obj ) { Type type = obj.GetType(); if ( type == typeof( MailMessage ) ) return 0; else if ( type == typeof( MultiMailMessage ) ) return 1; //else if ( type == typeof( AuctionMailMessage ) ) // return 2; return 0; }
protected override MailMessageSenderResult Transmit(IMailMessage msg) { System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); MailMessageAdapter.CopyMailMessage(msg, mailMessage); //string smtpHost = System.Configuration.ConfigurationManager.AppSettings["Mail.smtpServer"]; //int smtpPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Mail.smtpPort"]); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();//(smtpHost,smtpPort); client.Send(mailMessage); return(new MailMessageSenderResult(MailMessageSenderStatus.Sent, null, msg.Recipients, this.GetType())); }
/// <summary> /// Sends the specified message to an SMTP server for delivery. /// </summary> /// <param name="mailMessage"> /// A System.Net.Mail.MailMessage that contains the message to send. /// </param> /// <exception cref="InvalidOperationException"> /// This System.Net.Mail.SmtpClient has a Overload:System.Net.Mail.SmtpClient.SendAsync call in progress.-or- System.Net.Mail.MailMessage.From is null.-or- There are no recipients specified in System.Net.Mail.MailMessage.To, System.Net.Mail.MailMessage.CC, and System.Net.Mail.MailMessage.Bcc properties.-or- System.Net.Mail.SmtpClient.DeliveryMethod property is set to System.Net.Mail.SmtpDeliveryMethod.Network and System.Net.Mail.SmtpClient.Host is null.-or-System.Net.Mail.SmtpClient.DeliveryMethod property is set to System.Net.Mail.SmtpDeliveryMethod.Network and System.Net.Mail.SmtpClient.Host is equal to the empty string ("").-or- System.Net.Mail.SmtpClient.DeliveryMethod property is set to System.Net.Mail.SmtpDeliveryMethod.Network and System.Net.Mail.SmtpClient.Port is zero, a negative number, or greater than 65,535. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object has been disposed. /// </exception> /// <exception cref="SmtpException"> /// The connection to the SMTP server failed.-or-Authentication failed.-or-The operation timed out.-or-System.Net.Mail.SmtpClient.EnableSsl is set to true but the System.Net.Mail.SmtpClient.DeliveryMethod property is set to System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory or System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis.-or-System.Net.Mail.SmtpClient.EnableSsl is set to true, but the SMTP mail server did not advertise STARTTLS in the response to the EHLO command. /// </exception> /// /// <exception cref="SmtpFailedRecipientsException"> /// The message could not be delivered to one or more of the recipients in System.Net.Mail.MailMessage.To, System.Net.Mail.MailMessage.CC, or System.Net.Mail.MailMessage.Bcc. /// </exception> public void Send(IMailMessage mailMessage) { var message = new MailMessage(); foreach (var to in mailMessage.To) { message.To.Add(to.Address); } message.From = new MailAddress(mailMessage.From.Address); message.Subject = mailMessage.Subject; message.Body = mailMessage.Body; this.smtpClient.Send(message); }
public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); int dictcount = reader.ReadInt(); for (int i = 0; i < dictcount; i++) { IMailMessage message = NewMailMessage(reader.ReadByte(), reader.ReadInt()); message.Deserialize(reader); } }
public override void Send(IMailMessage message) { try { // log.Debug("Storing mail message"); store.Insert(CopyToStorableMailMessage(message)); //log.Debug("Mail message stored"); } catch (Exception e) { // log.Error("Error storing mail message", e); throw new MailException(e); } }
/// <summary> /// 读消息体 /// </summary> /// <param name="dataStream">数据流</param> /// <param name="message"></param> protected void ReadBody(ref Stream dataStream, ref IMailMessage message) { char[] buffer; int fulFilledCriteria; m_Criterias.Clear(); m_Criterias.Add(m_EndOfMessageStrategy); buffer = ReadData(ref dataStream, m_Criterias, out fulFilledCriteria); string body = new string(buffer); m_Source.Append(body); message.TextMessage = body; }
public bool Attached{ get{ return m_AttachedTo != null; } } //Used to find/delete orphaned containers. //Not constructable! public MailContainer( IMailMessage attached ) : base( 0xE75 ) { Movable = false; //Do not decay! MaxItems = 0; //Unlimited m_AttachedTo = attached; }
// (Microsoft.Exchange.WebServices.Data.EmailMessage m) /// <summary> /// process an email and call processAttachement for every attachement /// which fires an event for every new attachement /// </summary> /// <param name="m"></param> /// <returns></returns> public int processMail(IMailMessage m) { int iRet = 0; if (m == null) { utils.helpers.addLog("processMail: null msg"); OnStateChanged(new StatusEventArgs(StatusType.error, "NULL msg")); return iRet; } try { OnStateChanged(new StatusEventArgs(StatusType.none, "processing "+m.Attachements.Length.ToString()+" attachements" )); utils.helpers.addLog(m.User +","+ m.Subject + ", # attachements: " + m.Attachements.Length.ToString() + "\r\n"); //get data from email string sReceivededBy = m.User; DateTime dtSendAt = m.timestamp; //get data from body LicenseMailBodyData bodyData = new LicenseMailBodyData(); OnStateChanged(new StatusEventArgs(StatusType.none, "processing mail body")); utils.helpers.addLog("processing mail body"); bodyData = processMailBody(m); utils.helpers.addLog("mail body='" + m.Body + "'"); utils.helpers.addLog( bodyData.dump() ); if (m.Attachements.Length > 0) { //process each attachement foreach (Attachement a in m.Attachements) { try { utils.helpers.addLog("start processAttachement...\r\n"); iRet += processAttachement(a, bodyData, m); OnStateChanged(new StatusEventArgs(StatusType.none, "processed " + iRet.ToString() + " licenses")); utils.helpers.addLog("processAttachement done\r\n"); } catch (Exception ex) { utils.helpers.addExceptionLog(ex.Message); OnStateChanged(new StatusEventArgs(StatusType.error, "Exception1 in processAttachement: " + ex.Message)); } } } } catch (Exception ex) { utils.helpers.addLog("Exception: " + ex.Message); OnStateChanged(new StatusEventArgs(StatusType.error, "Exception2 in processAttachement: " + ex.Message)); } utils.helpers.addLog("processMail did process " + iRet.ToString() + " files"); return iRet; }
public static LicenseMailBodyData get(IMailMessage msg) { LicenseMailBodyData data = new LicenseMailBodyData(); string sBody = msg.Body; sBody = sBody.Replace("\r\n", ";"); var expression = new Regex( @"Order Number:[ ]+(?<order_number>[\S]+);" + @".+Order Date:[ ]+(?<order_date>[\S]+);" + @".+Your PO Number:[ ]+(?<po_number>[\S]+);"+ @".+End Customer:[ ]+(?<end_customer>[\S]+);"+ "" ); string currentMatch = "START"; string gMatch = ""; try { var match = expression.Match(sBody); currentMatch = "order_number"; //utils.helpers.addLog(string.Format("order_number......{0}", match.Groups["order_number"])); data.OrderNumber = match.Groups["order_number"].Value; currentMatch = "order_date"; //utils.helpers.addLog(string.Format("order_date........{0}", match.Groups["order_date"])); gMatch = match.Groups["order_date"].Value.TrimEnd(new char[] { ';' }); data.OrderDate = getDateTimeFromUSdateString(gMatch); currentMatch = "po_number"; //utils.helpers.addLog(string.Format("po_number........ {0}", match.Groups["po_number"])); data.yourPOnumber = match.Groups["po_number"].Value; currentMatch = "end_customer"; //utils.helpers.addLog(string.Format("end_customer..... {0}", match.Groups["end_customer"])); data.EndCustomer = match.Groups["end_customer"].Value; currentMatch = "Product"; expression = new Regex(@".+Product:[ ]+(?<product>.+);.+Quantity"); match = expression.Match(sBody); //utils.helpers.addLog(string.Format("product...........{0}", match.Groups["product"])); data.Product = match.Groups["product"].Value; currentMatch = "Quantity"; expression = new Regex(@".+Quantity:[ ]+(?<quantity>[0-9]+);"); match = expression.Match(sBody); //utils.helpers.addLog(string.Format("quantity..........{0}", match.Groups["quantity"])); data.Quantity = Convert.ToInt16(match.Groups["quantity"].Value.TrimEnd(new char[] { ';' })); } catch (Exception ex) { utils.helpers.addLog("Exception processing mail body regex: " + ex.Message + "\r\ncurrent expression: "+expression+"\r\ncurrentMatch: "+currentMatch); throw new FormatException("RegEx fails for MailBody"); } return data; }
public LicenseMail(IMailMessage msg) { ReceivedBy = msg.User; SendAt = msg.timestamp; }
public static LicenseMailBodyData processMailBody(IMailMessage msg) { LicenseMailBodyData bodyData = LicenseMailBodyData.get(msg); return bodyData; }
public static void SendMailWithBcc(MailAddress recipient, MailAddress bcc, IMailMessage message) { SendMailInternal(new MailAddress[] { recipient }, bcc, null, message); }
public static void RemoveMessage( IMailMessage message ) { m_MailMessages.Remove( message.Serial ); }
public int processAttachement(Attachement att, LicenseMailBodyData data, IMailMessage mail) { int iCount=0; LicenseXML xmlData = LicenseXML.Deserialize(att.data); foreach(license ldata in xmlData.licenses){ utils.helpers.addLog("processAttachement: new LicenseData...\r\n"); LicenseData licenseData = new LicenseData(ldata.id, ldata.user, ldata.key, data.OrderNumber, data.OrderDate, data.yourPOnumber, data.EndCustomer, data.Product, data.Quantity, mail.User, mail.timestamp); //if (_licenseDataBase.addQueued(licenseData)) utils.helpers.addLog("firing license_mail event\r\n"); OnStateChanged(new StatusEventArgs(StatusType.license_mail, licenseData)); iCount++; //if (_licenseDataBase.add(ldata.id, ldata.user, ldata.key, data.OrderNumber, data.OrderDate, data.yourPOnumber, data.EndCustomer, data.Product, data.Quantity, mail.User, mail.timestamp)) // iCount++; //utils.helpers.addLog("start _licenseDataBase.add() done\r\n"); } #region alternative_code /* // Request all the attachments on the email message. This results in a GetItem operation call to EWS. m.Load(new Microsoft.Exchange.WebServices.Data.PropertySet(Microsoft.Exchange.WebServices.Data.EmailMessageSchema.Attachments)); foreach (Microsoft.Exchange.WebServices.Data.Attachment att in m.Attachments) { if (att is Microsoft.Exchange.WebServices.Data.FileAttachment) { Microsoft.Exchange.WebServices.Data.FileAttachment fileAttachment = att as Microsoft.Exchange.WebServices.Data.FileAttachment; //get a temp file name string fname = System.IO.Path.GetTempFileName(); //utils.helpers.getAppPath() + fileAttachment.Id.ToString() + "_" + fileAttachment.Name // Load the file attachment into memory. This gives you access to the attachment content, which // is a byte array that you can use to attach this file to another item. This results in a GetAttachment operation // call to EWS. fileAttachment.Load(); // Load attachment contents into a file. This results in a GetAttachment operation call to EWS. fileAttachment.Load(fname); addLog("Attachement file saved to: " + fname); // Put attachment contents into a stream. using (System.IO.FileStream theStream = new System.IO.FileStream(utils.helpers.getAppPath() + fileAttachment.Id.ToString() + "_" + fileAttachment.Name, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite)) { //This results in a GetAttachment operation call to EWS. fileAttachment.Load(theStream); } //load into memory stream, seems the only stream supported using (System.IO.MemoryStream ms = new System.IO.MemoryStream(att.Size)) { fileAttachment.Load(ms); using (System.IO.FileStream fs = new System.IO.FileStream(fname, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite)) { ms.CopyTo(fs); fs.Flush(); } } addLog("saved attachement: " + fname); iRet++; } } */ #endregion return iCount; }
/// <summary> /// перегрузка имеющегося метода для отправки уведомлений с аттачами /// </summary> private static void SendMailInternal(MailAddress[] recipient, MailAddress bcc, MailAddress replyTo, Attachment[] attachments, IMailMessage message) { // Тут тоже самое что в методе SendMailInternal, но с вложениями MailData data = ConvertMailMessage(message); MailMessage msg = new MailMessage(); #region !!! UNCOMMENT FOR RELEASE !!! //Сделано для того чтобы с тестового сайта не шла рассылка существующим клиентам при //каких-либо манипуляциях с их заказами (т.к. тестовая база является копией боевой, то в ней лежат инфа о реальных заказах) foreach (MailAddress addr in recipient) msg.To.Add(addr); if (bcc != null) msg.Bcc.Add(bcc); msg.ReplyTo = replyTo; #endregion #region !!! COMMENT FOR RELEASE !!! ////Принудительна отсылка всех уведовлений на мой ящик, чтобы тестировать рассылки //msg.To.Add(new MailAddress("*****@*****.**")); //msg.To.Add(new MailAddress("*****@*****.**")); //msg.To.Add(new MailAddress("*****@*****.**")); #endregion msg.Subject = data.Subject; msg.Body = data.Body; msg.IsBodyHtml = true; //var attachAttributes = Attribute.GetCustomAttributes(message.GetType(), typeof(MailAttachmentAttribute)); //foreach (MailAttachmentAttribute item in attachAttributes) //{ // msg.Attachments.Add(new Attachment(new MemoryStream(item.Data), item.Name)); //} foreach (var item in attachments) { msg.Attachments.Add(item); } new SmtpClient().Send(msg); }
public static void SendMail(MailAddress recipient, IMailMessage message) { SendMailInternal(new MailAddress[] { recipient }, null, null, message); }
/// <summary> /// метод для замены метода SendMailWithBcc /// </summary> public static void SendMailWithBccAndAttachments(MailAddress recipient, MailAddress bcc, Attachment[] attachments, IMailMessage message) { SendMailInternal(new MailAddress[] { recipient }, bcc, null, attachments, message); }
private static void SendMailInternal(MailAddress[] recipient, MailAddress bcc, MailAddress replyTo, IMailMessage message) { MailData data = ConvertMailMessage( message ); MailMessage msg = new MailMessage(); #region !!! UNCOMMENT FOR RELEASE !!! //Сделано для того чтобы с тестового сайта не шла рассылка существующим клиентам при //каких-либо манипуляциях с их заказами (т.к. тестовая база является копией боевой, то в ней лежат инфа о реальных заказах) foreach (MailAddress addr in recipient) msg.To.Add(addr); if (bcc != null) msg.Bcc.Add(bcc); msg.ReplyTo = replyTo; #endregion #region !!! COMMENT FOR RELEASE !!! //Принудительна отсылка всех уведовлений на мой ящик, чтобы тестировать рассылки //msg.To.Add(new MailAddress("*****@*****.**")); //msg.To.Add(new MailAddress("*****@*****.**")); #endregion msg.Subject = data.Subject; msg.Body = data.Body; msg.IsBodyHtml = true; msg.From = new MailAddress("*****@*****.**"); var attachAttributes = Attribute.GetCustomAttributes( message.GetType(), typeof( MailAttachmentAttribute ) ); foreach( MailAttachmentAttribute item in attachAttributes ) { msg.Attachments.Add( new Attachment( new MemoryStream( item.Data ), item.Name ) ); } var cl =new SmtpClient(); cl.Credentials = new NetworkCredential("*****@*****.**", "db76as"); cl.Port = 25; cl.EnableSsl=true; cl.Host = "smtp.yandex.ru"; //cl.ClientCertificates //cl. cl.Send( msg ); }