/// <summary> /// Sends an email via G-Mail with the provided email settings. /// </summary> /// <param name="fromEmailAddress"></param> /// <param name="toEmailAddress"></param> /// <param name="subject"></param> /// <param name="messageBody"></param> /// <param name="password"></param> /// <returns></returns> public static void send(string fromEmailAddress, string fromName, string toEmailAddress, string subject, string messageBody, string password, string server, int port, int timeout) { CDO.Message smtp = new CDO.Message(); CDO.Configuration smtpConfig = new CDO.Configuration(); ADODB.Fields fieldCollection = smtpConfig.Fields; ADODB.Field serverField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/smtpserver"]; serverField.Value = server; ADODB.Field usernameField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/sendusername"]; usernameField.Value = fromEmailAddress; ADODB.Field passwordField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/sendpassword"]; passwordField.Value = password; ADODB.Field authField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"]; authField.Value = 1; ADODB.Field timeoutField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"]; timeoutField.Value = timeout; ADODB.Field serverPortField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/smtpserverport"]; serverPortField.Value = port; ADODB.Field sendUsingField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/sendusing"]; sendUsingField.Value = 2; ADODB.Field useSSLField = fieldCollection["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]; useSSLField.Value = 1; fieldCollection.Update(); smtp.Configuration = smtpConfig; smtp.Subject = subject; smtp.From = fromEmailAddress; smtp.To = toEmailAddress; smtp.Sender = fromName; smtp.Organization = fromName; smtp.ReplyTo = fromEmailAddress; smtp.TextBody = messageBody; smtp.Send(); }
public int SendMail(MailAccount Sender, MailAccount Receiver, string mailSubject) { //获得要处理的邮件信 try { string mailUser = Sender.UserName; string mailPass = Sender.Password; string mailFrom = Sender.UserName; string smtpserver = Sender.SmtpHost; CDO.Message message = new CDO.Message(); message.To = Receiver.UserName; message.TextBody = "Test Send"; //邮件标题 message.Subject = "Test"; message.From = Sender.UserName; message.Sender = Sender.UserName; CDO.IConfiguration iConfig = message.Configuration; ADODB.Fields fields = iConfig.Fields; fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = mailFrom; fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = mailFrom; fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = mailPass; fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1; fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = smtpserver; fields.Update(); message.Send(); message = null; return 0; } catch (Exception ex) { return -1; } }
/// <summary> /// 下载web方法 /// </summary> /// <param name="url">url是要保存的网页地址</param> /// <param name="filePath">filePath是保存到的文件路径</param> /// <returns></returns> public static bool SaveWebPageToMHTFile(string url, string filePath) { bool result = false; //CDO.Message msg = new CDO.MessageClass(); CDO.Message msg = new CDO.Message(); //ADODB.Stream stm = null; try { msg.MimeFormatted = true; msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", ""); //stm = msg.GetStream(); //stm.SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); msg.GetStream().SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); msg = null; //stm.Close(); result = true; } catch //(Exception ex) { } finally { //cleanup here } return result; }
/// <summary> /// 发送EMAIL /// </summary> /// <param name="message">MailMessage</param> /// <param name="smtp">SmtpClient</param> /// <returns>true/false</returns> public bool Send(System.Net.Mail.MailMessage message, System.Net.Mail.SmtpClient smtp) { try { //Msg.Write("Host:{0}<br />".FormatWith(smtp.Host)); //Msg.Write("Port:{0}<br />".FormatWith(smtp.Port)); //Msg.Write("From:{0}<br />".FormatWith(message.From.ToJson())); //Msg.Write("Body:{0}<br />".FormatWith(message.Body)); //Msg.Write("Subject:{0}<br />".FormatWith(message.Subject)); //Msg.Write("IsBodyHtml:{0}<br />".FormatWith(message.IsBodyHtml)); //Msg.Write("Credentials:{0}<br />".FormatWith(smtp.Credentials.GetCredential(smtp.Host, smtp.Port, "").ToJson())); //Msg.Write("To:{0}<br />".FormatWith(message.To.ToJson())); //Msg.Write("Cc:{0}<br />".FormatWith(message.CC.ToJson())); StringBuilder toList = new StringBuilder(); message.To.Do(p => toList.Append(p.Address).Append(";")); StringBuilder ccList = new StringBuilder(); message.CC.Do(p => ccList.Append(p.Address).Append(";")); CDO.Message objMail = new CDO.Message(); objMail.To = toList.ToStr(); objMail.CC = ccList.ToStr(); objMail.From = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); objMail.Subject = message.Subject; if (message.IsBodyHtml) objMail.HTMLBody = message.Body; else objMail.TextBody = message.Body; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = smtp.Port; //设置端口 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = smtp.Host; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 10; if (!smtp.UseDefaultCredentials) { NetworkCredential n = smtp.Credentials.GetCredential(smtp.Host, smtp.Port, ""); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = n.UserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = n.UserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = n.Password; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1; } else { objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 0; } objMail.Configuration.Fields.Update(); objMail.Send(); System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); return true; } catch(Exception ex) { errorMessage = ex.ToExceptionDetail(); return false; } finally { message = null; smtp = null; } }
protected CDO.Message ReadMessage(ADODB.Stream stream) { CDO.Message msg = new CDO.Message(); msg.DataSource.OpenObject(stream, "_Stream"); msg.DataSource.Save(); return(msg); }
public void ProcessCDOMessage(CDO.Message message) { try { this.Agent.ProcessMessage(message); } catch (Exception ex) { Logger.Fatal("While ProcessCDOMessage", ex); // // Paranoia of last resort. A malconfigured or malfunctioning agent should NEVER let ANY messages through // try { message.AbortMessage(); } catch (Exception ex2) { Logger.Fatal("While aborting message", ex2); } throw; } }
/// <summary> /// 下载web方法 /// </summary> /// <param name="url">url是要保存的网页地址</param> /// <param name="filePath">filePath是保存到的文件路径</param> /// <returns></returns> public static bool SaveWebPageToMHTFile(string url, string filePath) { bool result = false; //CDO.Message msg = new CDO.MessageClass(); CDO.Message msg = new CDO.Message(); //ADODB.Stream stm = null; try { msg.MimeFormatted = true; msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", ""); //stm = msg.GetStream(); //stm.SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); msg.GetStream().SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); msg = null; //stm.Close(); result = true; } catch //(Exception ex) { } finally { //cleanup here } return(result); }
public static void SendEmailByCdo(string operation, string email, string msg) { CDO.Message objMail = new CDO.Message(); try { objMail.To = email; objMail.From = "*****@*****.**"; objMail.Subject = operation; //邮件主题 objMail.HTMLBody = msg; //邮件内容 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = 465; //设置端口 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = "smtp.163.com"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = "*****@*****.**"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = "*****@*****.**"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = "*****@*****.**"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = "*****@*****.**"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = "a2151888"; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = "true";//这一句指示是否使用ssl objMail.Configuration.Fields.Update(); objMail.Send(); } catch (Exception ex) { throw ex; } finally { } System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); objMail = null; }
///// <summary> ///// 发送EMAIL ///// </summary> ///// <param name="toEmail">EMAIL</param> ///// <returns>是否成功</returns> //public bool Send2(string toEmail) { // ISmtpMail ESM = new SmtpMail(); // try { // //ESM.RecipientName = toEmail; // ESM.AddRecipient(new string[] { toEmail }); // ESM.MailDomainPort = 25; // ESM.Html = bool.Parse("true"); // ESM.Subject = _Subject; // ESM.Body = _Body; // //ESM.FromName = WebConfig.GetApp("FromEmail"); // ESM.From = _FromEmail; // ESM.MailDomain = _SmtpServer; // ESM.MailServerUserName = _SmtpUserName; // ESM.MailServerPassWord = _SmtpPassword; // return ESM.Send(); // } catch { return false; } //} /// <summary> /// 发送EMAIL /// </summary> /// <param name="toEmail">Email</param> /// <returns>是否成功</returns> public bool CDOMessageSend(string toEmail) { lock (lockHelper) { CDO.Message objMail = new CDO.Message(); try { objMail.To = toEmail; objMail.From = _FromEmail; objMail.Subject = _Subject; if (_Format.Equals(System.Web.Mail.MailFormat.Html)) { objMail.HTMLBody = _Body; } else { objMail.TextBody = _Body; } //if (!_SmtpPort.Equals("25")) objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = _SmtpPort; //设置端口 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = _SmtpServer; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 1; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 10; objMail.Configuration.Fields.Update(); objMail.Send(); return(true); } catch {} finally{ } System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); objMail = null; } return(false); }
private void RunMdnProcessingForMissingStart(IEnumerable <NotificationMessage> notificationMessages) { foreach (var notification in notificationMessages) { var mdnText = MimeSerializer.Default.Serialize(notification); CDO.Message message = LoadMessage(mdnText); m_agent.ProcessMessage(message); //Loop back so it is encrypted message = LoadMessage(message); VerifyOutgoingMessage(message); //Encrypted m_agent.ProcessMessage(message); message = LoadMessage(message); //Decrypted VerifyIncomingMessage(message); //Can't ensure message is deleted in this test because IIS SMTP is not hosting SmtpAgent. // // assert not in the monitor store. // var queryMdn = BuildMdnQueryFromMdn(LoadMessage(mdnText)); queryMdn.Status = MdnStatus.Started; var mdnManager = CreateConfigStore().Mdns; var mdn = mdnManager.Get(queryMdn.MdnIdentifier); Assert.Null(mdn); } }
public void SendCDO(string to) { try { CDO.Message msg = new CDO.Message(); CDO.IConfiguration iConfig; iConfig = msg.Configuration; ADODB.Fields oFields; oFields = iConfig.Fields; ADODB.Field oField = oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"]; //oField.Value = 2; //oField = oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"]; //oField.Value = "smtp.gmail.com"; //oField = oFields["http://schemas.microsoft.com/cdo/configuration/stmpserverport"]; //oField.Value = 25; oFields.Update(); msg.Subject = "Prueba"; msg.From = "*****@*****.**"; msg.To = to; msg.TextBody = "Mensaje de pueba"; msg.Send(); Console.WriteLine("Mensaje enviado"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// 发送EMAIL /// </summary> /// <param name="message">MailMessage</param> /// <param name="smtp">SmtpClient</param> /// <returns>true/false</returns> public bool Send(System.Net.Mail.MailMessage message, System.Net.Mail.SmtpClient smtp) { try { //Msg.Write("Host:{0}<br />".FormatWith(smtp.Host)); //Msg.Write("Port:{0}<br />".FormatWith(smtp.Port)); //Msg.Write("From:{0}<br />".FormatWith(message.From.ToJson())); //Msg.Write("Body:{0}<br />".FormatWith(message.Body)); //Msg.Write("Subject:{0}<br />".FormatWith(message.Subject)); //Msg.Write("IsBodyHtml:{0}<br />".FormatWith(message.IsBodyHtml)); //Msg.Write("Credentials:{0}<br />".FormatWith(smtp.Credentials.GetCredential(smtp.Host, smtp.Port, "").ToJson())); //Msg.Write("To:{0}<br />".FormatWith(message.To.ToJson())); //Msg.Write("Cc:{0}<br />".FormatWith(message.CC.ToJson())); StringBuilder toList = new StringBuilder(); message.To.Do(p => toList.Append(p.Address).Append(";")); StringBuilder ccList = new StringBuilder(); message.CC.Do(p => ccList.Append(p.Address).Append(";")); CDO.Message objMail = new CDO.Message(); objMail.To = toList.ToStr(); objMail.CC = ccList.ToStr(); objMail.From = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); objMail.Subject = message.Subject; if (message.IsBodyHtml) { objMail.HTMLBody = message.Body; } else { objMail.TextBody = message.Body; } objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = smtp.Port; //设置端口 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = smtp.Host; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 10; if (!smtp.UseDefaultCredentials) { NetworkCredential n = smtp.Credentials.GetCredential(smtp.Host, smtp.Port, ""); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = "\"{0}\"<{1}>".FormatWith(message.From.DisplayName, message.From.Address); //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = n.UserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = n.UserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = n.Password; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1; } else { objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 0; } objMail.Configuration.Fields.Update(); objMail.Send(); System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); return(true); } catch (Exception ex) { errorMessage = ex.ToExceptionDetail(); return(false); } finally { message = null; smtp = null; } }
public void TestEndToEnd(string messageText) { CDO.Message message = this.LoadMessage(messageText); string originalSubject = message.Subject; string originalContentType = message.GetContentType(); // // Outgoing // Assert.DoesNotThrow(() => m_handler.ProcessCDOMessage(message)); message = this.LoadMessage(message); // re-load the message base.VerifyOutgoingMessage(message); // // Incoming // Assert.DoesNotThrow(() => m_handler.ProcessCDOMessage(message)); message = this.LoadMessage(message); // re-load the message base.VerifyIncomingMessage(message); Assert.True(message.Subject.Equals(originalSubject)); Assert.True(MimeStandard.Equals(message.GetContentType(), originalContentType)); Message mailMessage = MailParser.ParseMessage(message.GetMessageText()); string header = mailMessage.Headers.GetValue(SmtpAgent.XHeaders.Receivers); Assert.DoesNotThrow(() => MailParser.ParseAddressCollection(header)); MailAddressCollection addresses = MailParser.ParseAddressCollection(header); Assert.True(addresses.Count > 0); }
public void TestFinalDestinationDelivery(string unDeliverableRecipientMessage, List <DSNPerRecipient> perRecipientExpected) { CleanMessages(m_agent.Settings); CleanMonitor(); m_agent.Settings.InternalMessage.EnableRelay = true; m_agent.Settings.Notifications.AutoResponse = true; m_agent.Settings.Notifications.AlwaysAck = true; // // Do not need to set AutoDsnOption to TimelyAndReliable as it is the default setting. // //m_agent.Settings.Notifications.AutoDsnFailureCreation = // NotificationSettings.AutoDsnOption.TimelyAndReliable.ToString(); m_agent.Settings.AddressManager = new ClientSettings(); m_agent.Settings.AddressManager.Url = "http://localhost/ConfigService/DomainManagerService.svc/Addresses"; m_agent.Settings.MdnMonitor = new ClientSettings(); m_agent.Settings.MdnMonitor.Url = "http://localhost/ConfigService/MonitorService.svc/Dispositions"; foreach (FolderRoute route in m_agent.Settings.IncomingRoutes.Where(route => route.AddressType == "Throw")) { route.CopyMessageHandler = ThrowCopy; } // // Process loopback messages. Leaves un-encrypted mdns in pickup folder // Go ahead and pick them up and Process them as if they where being handled // by the SmtpAgent by way of (IIS)SMTP hand off. // var sendingMessage = LoadMessage(unDeliverableRecipientMessage); Assert.Null(Record.Exception(() => RunEndToEndTest(sendingMessage))); var foundDsn = false; foreach (var pickupMessage in PickupMessages()) { string messageText = File.ReadAllText(pickupMessage); CDO.Message cdoMessage = LoadMessage(messageText); var message = new CDOSmtpMessage(cdoMessage).GetEnvelope(); if (message.Message.IsDSN()) { foundDsn = true; var dsn = DSNParser.Parse(message.Message); foreach (var perRecipient in dsn.PerRecipient) { Assert.Equal(perRecipientExpected.Count, dsn.PerRecipient.Count()); string finalRecipient = perRecipient.FinalRecipient.Address; var expectedPerRecipient = perRecipientExpected.Find(d => d.FinalRecipient.Address == finalRecipient); Assert.Equal(expectedPerRecipient.Action, perRecipient.Action); Assert.Equal(expectedPerRecipient.Status, perRecipient.Status); } } } Assert.True(foundDsn); m_agent.Settings.InternalMessage.EnableRelay = false; }
/// <summary> /// Sends the email or SMS. /// </summary> /// <param name="address">The address.</param> /// <param name="subject">The subject.</param> /// <param name="textBody">The text body.</param> /// <param name="useMailOrSms">if set to <c>true</c> [use email or SMS].</param> /// <param name="isAutomaticMail">if set to <c>true</c> [is automatic mail].</param> /// <param name="attachmentFilePath">The attachment file path.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> public static bool SendEmail(string address, string subject, string textBody, bool useMailOrSms, bool isAutomaticMail, string attachmentFilePath = null) { bool useMail = Settings.Default.UseMail; if (!useMail || !useMailOrSms || String.IsNullOrEmpty(address)) return false; try { var message = new CDO.Message(); message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = SmtpServer; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = SmtpServerPort; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = SendUsing; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = SmtpAuthenticate; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = SendUserName; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = SendPassword; message.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = SmtpUseSsl; message.Configuration.Fields.Update(); message.From = SendUserName; message.To = address; message.Subject = String.Format("{0}{1}", Settings.Default.EmailPrefix, subject); message.BodyPart.Charset = "UTF-8"; Encoding defaultEncoding = Encoding.Default; Encoding utf8 = Encoding.UTF8; string wholeTextBody = isAutomaticMail ? String.Format(MailResource.Mail_AutomaticMailTextBodyTemplate, textBody) : textBody; byte[] defaultBytes = defaultEncoding.GetBytes(wholeTextBody); byte[] uftBytes = Encoding.Convert(defaultEncoding, utf8, defaultBytes); var utfChars = new char[utf8.GetCharCount(uftBytes, 0, uftBytes.Length)]; utf8.GetChars(uftBytes, 0, uftBytes.Length, utfChars, 0); var text = new string(utfChars); message.TextBody = text; if (!String.IsNullOrEmpty(attachmentFilePath)) { message.AddAttachment(attachmentFilePath); } message.Send(); ReleaseComObject(message); } catch (Exception e) { var logParameter = new Logger.LogParameter {AdditionalMessage = String.Format("address: {0}", address)}; Logger.SetLog(e, logParameter); return false; } return true; }
internal void VerifyOutgoingMessage(CDO.Message message) { Assert.True(string.IsNullOrEmpty(message.Subject)); ContentType contentType = new ContentType(message.GetContentType()); Assert.True(SMIMEStandard.IsContentEncrypted(contentType)); }
public CDOMessageConverter(string mailContent) { cdoMessage = new CDO.Message(); ADODB.Stream adoStream = cdoMessage.GetStream(); adoStream.Type = ADODB.StreamTypeEnum.adTypeText; adoStream.WriteText(mailContent.Trim(), ADODB.StreamWriteEnum.adWriteLine); adoStream.Flush(); adoStream.Close(); }
public void CDOEXSendEmail(String recipient) { CDO.Message objMessage = new CDO.Message(); objMessage.From = "*****@*****.**"; objMessage.To = recipient; objMessage.Subject = "Testing some CDOEX functionality"; objMessage.TextBody = "Yup, it seems to be working ok!\r\n\r\nCheers,\r\nMikael"; objMessage.Send(); }
public AlertSendStatus Send() { AlertSendStatus alertSendStatus = new AlertSendStatus { IsSend = false, ProviderMessage = "Waiting" }; try { CDO.Message oMsg = new CDO.Message(); CDO.IConfiguration iConfg; iConfg = oMsg.Configuration; ADODB.Fields oFields; oFields = iConfg.Fields; // Set configuration. oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = "smtp.gmail.com"; oFields["http://schemas.microsoft.com/cdo/configuration/smptserverport"].Value = 587; oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1; oFields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = true; oFields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 60; oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = "*****@*****.**"; oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = "drone123"; oFields.Update(); oMsg.CreateMHTMLBody(emailMessage.EmailURL); oMsg.Subject = emailMessage.EmailSubject; //TODO: Change the To and From address to reflect your information. oMsg.From = "Exponent <*****@*****.**>"; oMsg.To = emailMessage.ToAddress; //ADD attachment. //TODO: Change the path to the file that you want to attach. if (!String.IsNullOrEmpty(emailMessage.Attachments)) { foreach (String FileWithPath in emailMessage.Attachments.Split(',')) { oMsg.AddAttachment(FileWithPath); } } oMsg.Send(); alertSendStatus.IsSend = true; alertSendStatus.ProviderMessage = "Send Successfully"; } catch (Exception e) { alertSendStatus.ProviderMessage = e.Message; } return(alertSendStatus); }
static void TestMdnsInProcessedStatus(CDO.Message message, bool timelyAndReliable) { var queryMdn = BuildMdnQueryFromMdn(message); queryMdn.Status = MdnStatus.Processed; var mdnManager = CreateConfigStore().Mdns; var mdn = mdnManager.Get(queryMdn.MdnIdentifier); Assert.NotNull(mdn); Assert.Equal("processed", mdn.Status, StringComparer.OrdinalIgnoreCase); Assert.Equal(timelyAndReliable, mdn.NotifyDispatched); }
protected static Mdn BuildQueryFromDSN(CDO.Message message) { var messageEnvelope = new CDOSmtpMessage(message).GetEnvelope(); Assert.True(messageEnvelope.Message.IsDSN()); var mimeMessage = messageEnvelope.Message; var messageId = mimeMessage.IDValue; string sender = messageEnvelope.Sender.Address; string recipient = messageEnvelope.Recipients[0].Address; return(new Mdn(messageId, recipient, sender)); }
public void TestEndToEnd_GatewayIsDestination_Is_True_And_TimelyAndReliable_Not_Requestd() { CleanMessages(m_agent.Settings); m_agent.Settings.InternalMessage.EnableRelay = true; m_agent.Settings.Outgoing.EnableRelay = true; m_agent.Settings.Notifications.AutoResponse = true; m_agent.Settings.Notifications.AlwaysAck = true; m_agent.Settings.Notifications.GatewayIsDestination = true; // // Process loopback messages. Leaves un-encrypted mdns in pickup folder // Go ahead and pick them up and Process them as if they where being handled // by the SmtpAgent by way of (IIS)SMTP hand off. // string textMessage = string.Format(string.Format(TestMessageHsmToSoft, Guid.NewGuid()), Guid.NewGuid()); var sendingMessage = LoadMessage(textMessage); RunEndToEndTest(sendingMessage, m_agent); // // grab the clear text mdns and delete others. // foreach (var pickupMessage in PickupMessages()) { string messageText = File.ReadAllText(pickupMessage); if (messageText.Contains("disposition-notification")) { RunMdnOutBoundProcessingTest(LoadMessage(messageText), m_agent); } } // // Now the messages are encrypted and can be handled // Processed Mdn's will be recorded by the MdnMonitorService // foreach (var pickupMessage in PickupMessages()) { string messageText = File.ReadAllText(pickupMessage); CDO.Message message = LoadMessage(messageText); RunMdnInBoundProcessingTest(message, m_agent); var envelope = new CDOSmtpMessage(message).GetEnvelope(); var mdn = MDNParser.Parse(envelope.Message); // // Only expect processed MDNs // Assert.Equal(MDNStandard.NotificationType.Processed, mdn.Disposition.Notification); TestMdnTimelyAndReliableExtensionField(mdn, false); } m_agent.Settings.InternalMessage.EnableRelay = false; }
protected static Mdn BuildMdnQueryFromMdn(CDO.Message message) { var messageEnvelope = new CDOSmtpMessage(message).GetEnvelope(); Assert.True(messageEnvelope.Message.IsMDN()); var notification = MDNParser.Parse(messageEnvelope.Message); var originalMessageId = notification.OriginalMessageID; string originalSender = messageEnvelope.Recipients[0].Address; string originalRecipient = messageEnvelope.Sender.Address; return(new Mdn(originalMessageId, originalRecipient, originalSender)); }
protected override void ImportStream(PipelineContext ctx, IDatasourceSink sink, IStreamProvider elt, Stream strm) { CDO.IMessage msg = new CDO.Message(); msg.DataSource.OpenObject(new IStreamFromStream(strm), "IStream"); sink.HandleValue(ctx, "record/subject", msg.Subject); sink.HandleValue(ctx, "record/bcc", msg.BCC); sink.HandleValue(ctx, "record/cc", msg.CC); sink.HandleValue(ctx, "record/from", msg.From); sink.HandleValue(ctx, "record/to", msg.To); Utils.FreeAndNil(ref msg); sink.HandleValue(ctx, "record", null); }
protected void btnSubmit_Click(object sender, EventArgs e) { dynamic objMail = new CDO.Message(); try { if (txtValidation.Text == "30") { dynamic fromAddress = "*****@*****.**"; const string fromPassword = "******"; dynamic toAddress = "*****@*****.**"; string subject = "Test"; dynamic EnableSsl = true; dynamic smtpServer = "smtp.exmail.qq.com"; dynamic smtpPort = "465"; string body = "" + "\r\n"; body += "------------------------------------TrustPLus Main Page Email------------------------------------" + "\r\n"; body += "Customer Name: " + txtName.Text + "\r\n"; body += "Customer Cell: " + txtPhoneNumber.Text + "\r\n"; body += "Customer Email: " + txtEmail.Text + "\r\n"; body += "Title: " + "正信网站客户信息" + "\r\n"; body += "---------" + "\r\n"; body += "Message: " + txtEmailMessage.Text; //here on button click what will done //SendMail() objMail.To = toAddress; objMail.From = fromAddress; objMail.Subject = subject; //objMail.HTMLBody = body objMail.TextBody = body; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport").Value = smtpPort; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpServer; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendemailaddress").Value = fromAddress; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress").Value = toAddress; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpaccountname").Value = fromAddress objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername").Value = fromAddress; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword").Value = fromPassword; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = 2; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate").Value = 1; objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl").Value = EnableSsl; objMail.Configuration.Fields.Update(); objMail.Send(); } else { txtEmail.Focus(); } } catch (Exception) { } System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); }
private CDO.Message GetMessage(FileInfo fileInfo) { CDO.Message msg = new CDO.Message(); ADODB.Stream stream = new ADODB.Stream(); stream.Type = StreamTypeEnum.adTypeBinary; stream.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty); stream.LoadFromFile(fileInfo.FullName); stream.Flush(); msg.DataSource.OpenObject(stream, "_Stream"); msg.DataSource.Save(); return(msg); }
//--------------------------------------------------- // // Message Processing // //--------------------------------------------------- public void ProcessMessage(CDO.Message message) { try { this.ProcessMessage(new CDOSmtpMessage(message)); } catch { // Paranoia message.AbortMessage(); throw; } }
protected int GetPublisherIdFromLogs(CDO.Message message) { var emailHeaders = GetEmailHeaders(message); var receivedHeader = emailHeaders.Find(x => x.HeaderName == "urn:schemas:mailheader:received"); Regex regex = new Regex(@"\[\d+\.\d+\.\d+\.\d+\]"); MatchCollection matches = regex.Matches(receivedHeader.HeaderValue); if (matches.Count != 1) { return(0); } string dateString = string.Format("{0:yyy-MM-dd}", message.ReceivedTime); string receivedFropIp = matches[0].Value.Substring(1, matches[0].Value.Length - 2); string plusAddressingTemplate = string.Format("\"{0}\" \"RECEIVED: RCPT TO:<", receivedFropIp); string logFilePath = AppSettingsHelper.GetValueFromAppSettings(Common.Enums.AppSettingsKey.hMailServerLogsFolder); string lofFileName = string.Format("hmailserver_{0}.log", dateString); int result = 0; using (StreamReader file = new StreamReader(Path.Combine(logFilePath, lofFileName))) { string line = string.Empty; while ((line = file.ReadLine()) != null) { if (line.IndexOf(plusAddressingTemplate) != -1) { int lineDateStartIndex = line.IndexOf(dateString); if (lineDateStartIndex == -1) { continue; } string dateTimeString = line.Substring(lineDateStartIndex, line.Length - lineDateStartIndex); dateTimeString = dateTimeString.Substring(0, dateTimeString.IndexOf('"')); DateTime fileReceivedTime = Convert.ToDateTime(dateTimeString); long diff = message.ReceivedTime.Ticks - fileReceivedTime.Ticks; diff = diff < 0 ? -diff : diff; if (diff < (10000000 * 5)) { string errorMsg = string.Empty; result = GetPublisherIdFromEmailString(line, out errorMsg); } } } } return(result); }
public List <Common.Models.EmailHeader> GetEmailHeaders(CDO.Message message) { var result = new List <Common.Models.EmailHeader>(); var fields = message.Fields; foreach (dynamic item in message.Fields) { result.Add(new Common.Models.EmailHeader() { HeaderName = item.Name == null?"":item.Name, HeaderValue = item.Value == null?"":item.Value.ToString() }); } return(result); }
/// <summary> /// Sends the email MHTML. /// </summary> /// <param name="message">The message.</param> public virtual void SendMhtml(MailMessage message) { lock (_lock) try { var m = new CDO.Message(); // set message var s = new ADODB.Stream(); s.Charset = "ascii"; s.Open(); s.WriteText(message.Body); m.DataSource.OpenObject(s, "_Stream"); // set configuration var f = m.Configuration.Fields; switch (DeliveryMethod) { case SmtpDeliveryMethod.Network: f["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = CDO.CdoSendUsing.cdoSendUsingPort; f["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = Host; break; case SmtpDeliveryMethod.SpecifiedPickupDirectory: f["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = CDO.CdoSendUsing.cdoSendUsingPickup; f["http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory"].Value = PickupDirectoryLocation; break; default: throw new NotSupportedException(); } f.Update(); // set other values m.MimeFormatted = true; m.Subject = message.Subject; if (message.From != null) m.From = message.From.ToString(); var to = (message.To != null ? string.Join(",", message.To.Select(x => x.ToString()).ToArray()) : null); if (!string.IsNullOrEmpty(to)) m.To = to; var bcc = (message.Bcc != null ? string.Join(",", message.Bcc.Select(x => x.ToString()).ToArray()) : null); if (!string.IsNullOrEmpty(to)) m.BCC = bcc; var cc = (message.CC != null ? string.Join(",", message.CC.Select(x => x.ToString()).ToArray()) : null); if (!string.IsNullOrEmpty(to)) m.CC = cc; if (message.Attachments != null) foreach (var attachment in message.Attachments.Where(x => x != null)) AddAttachement(m, attachment, false); m.Send(); } catch (Exception ex) { throw ex; } }
public bool Receive(ISmtpMessage message) { CDOSmtpMessage cdoSmtpMessage = message as CDOSmtpMessage; CDO.Message cdoMessage = null; if (cdoSmtpMessage != null) { cdoMessage = cdoSmtpMessage.InnerMessage; } if (cdoMessage == null) { cdoMessage = Extensions.LoadCDOMessageFromText(message.GetMessageText()); } cdoMessage.Send(this.Settings.Server, this.Settings.Port); return(true); }
/// <summary> /// 专门针对办公网的下载web方法 /// </summary> /// <param name="url">url是要保存的网页地址</param> /// <param name="filePath">filePath是保存到的文件路径</param> /// <returns></returns> public static bool SaveOaWebPageToMHTFile(string url, string filePath) { bool result = false; CDO.Message msg = new CDO.Message(); ADODB.Stream stm = null; msg.Configuration = new CDO.Configuration(); try { msg.MimeFormatted = true; msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", ""); if (url.Substring(0, cConfig.strOaURL.Length) == cConfig.strOaURL) { stm = msg.GetStream(); stm.Charset = "GB2312"; using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { string s = Regex.Replace(stm.ReadText(), "<img width=\\\"100%\\\" height=\\\"100\\\"(.[^>]*)>", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<P(.[^>]*)>", "<P>", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<a(.[^>]*)javascript:window.close(.[^>]*)><img src=(.[^>]*)>", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<table width=\\\"98%\\\"(.[^>]*)>", "", RegexOptions.IgnoreCase); byte[] array = Encoding.Default.GetBytes(s); fs.Write(array, 0, array.Length); //fs.Close(); } stm.Close(); } else { msg.GetStream().SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); } msg = null; result = true; } catch //(Exception ex) { } finally { //cleanup here } return(result); }
public IActionResult Index() { var myMail = new CDO.Message(); myMail.Subject = "Sending email with CDO"; myMail.From = "*****@*****.**"; myMail.To = "*****@*****.**"; myMail.HTMLBody = "<h1>This is a message.</h1>"; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = "localhost"; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = 25; myMail.Configuration.Fields.Update(); myMail.Send(); myMail = null; return(View()); }
protected void Page_Load(object sender, EventArgs e) { dynamic objMail = new CDO.Message(); try { //dynamic fromAddress = "*****@*****.**"; //const string fromPassword = "******"; //dynamic toAddress = "*****@*****.**"; //string subject = "Test"; //dynamic EnableSsl = true; //dynamic smtpServer = "smtp.exmail.qq.com"; //dynamic smtpPort = "465"; //string body = "" + "\r\n"; //body += "------------------------------------TrustPLus HousingTrust Email------------------------------------" + "\r\n"; //body += "Customer Name: " + Convert.ToString(txtName.Text) + "\r\n"; //body += "Customer Cell: " + Convert.ToString(txtPhone.Text) + "\r\n"; //body += "Customer Email: " + Convert.ToString(txtEmail.Text) + "\r\n"; //body += "Title: " + "Housing Trust Customer Information" + "\r\n"; //body += "---------" + "\r\n"; //body += "Message: " + Convert.ToString(txtMessage.Text); ////here on button click what will done ////SendMail() //objMail.To = toAddress; //objMail.From = fromAddress; //objMail.Subject = subject; ////objMail.HTMLBody = body //objMail.TextBody = body; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport").Value = smtpPort; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpServer; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendemailaddress").Value = fromAddress; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress").Value = toAddress; ////objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpaccountname").Value = fromAddress //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername").Value = fromAddress; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword").Value = fromPassword; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = 2; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate").Value = 1; //objMail.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl").Value = EnableSsl; //objMail.Configuration.Fields.Update(); //objMail.Send(); } catch (Exception) { } System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var myMail = new CDO.Message(); myMail.Subject = "Sending email with CDO"; myMail.From = "*****@*****.**"; myMail.To = "*****@*****.**"; myMail.HTMLBody = "<h1>This is a message.</h1>"; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = "localhost"; myMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = 25; myMail.Configuration.Fields.Update(); myMail.Send(); myMail = null; }
/// <summary> /// 专门针对办公网的下载web方法 /// </summary> /// <param name="url">url是要保存的网页地址</param> /// <param name="filePath">filePath是保存到的文件路径</param> /// <returns></returns> public static bool SaveOaWebPageToMHTFile(string url, string filePath) { bool result = false; CDO.Message msg = new CDO.Message(); ADODB.Stream stm = null; msg.Configuration = new CDO.Configuration(); try { msg.MimeFormatted = true; msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressNone, "", ""); if (url.Substring(0,cConfig.strOaURL.Length) == cConfig.strOaURL) { stm = msg.GetStream(); stm.Charset = "GB2312"; using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { string s = Regex.Replace(stm.ReadText(), "<img width=\\\"100%\\\" height=\\\"100\\\"(.[^>]*)>", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<P(.[^>]*)>", "<P>", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<a(.[^>]*)javascript:window.close(.[^>]*)><img src=(.[^>]*)>", "", RegexOptions.IgnoreCase); s = Regex.Replace(s, "<table width=\\\"98%\\\"(.[^>]*)>", "", RegexOptions.IgnoreCase); byte[] array = Encoding.Default.GetBytes(s); fs.Write(array, 0, array.Length); //fs.Close(); } stm.Close(); } else { msg.GetStream().SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); } msg = null; result = true; } catch //(Exception ex) { } finally { //cleanup here } return result; }
/// <summary> ///Updated Method,Send Mail with CDO method /// </summary> /// <param name="stage"></param> /// <param name="zipAttch"></param> /// <param name="reportFileName"></param> public static void EmailNotification(string stage, bool zipAttch, string reportFileName = null) { if (ValidateEmail() == false) return; Console.WriteLine(ConsoleMessages.MSG_DASHED); Console.WriteLine("Sending Email ....!!!"); Console.WriteLine(ConsoleMessages.MSG_DASHED); try { string[] emailStr = null; switch (stage.ToLower()) { case "start": emailStr = EmailTemplate(Property.EmailStartTemplate); break; case "end": emailStr = EmailTemplate(Property.EmailEndTemplate); break; } #region Email Configuration settings CDO.Message message = new CDO.Message(); CDO.IConfiguration configuration = message.Configuration; ADODB.Fields fields = configuration.Fields; ADODB.Field field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"]; field.Value = GetParameter("EmailSMTPServer").Trim(); field = fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"]; field.Value = int.Parse(GetParameter("EmailSMTPPort").Trim()); field = fields["http://schemas.microsoft.com/cdo/configuration/sendusing"]; field.Value = CDO.CdoSendUsing.cdoSendUsingPort; field = fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"]; field.Value = CDO.CdoProtocolsAuthentication.cdoBasic; field = fields["http://schemas.microsoft.com/cdo/configuration/sendusername"]; field.Value = GetParameter("EmailSMTPUsername").Trim(); field = fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"]; field.Value = GetParameter("EmailSMTPPassword").Trim(); field = fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"]; field.Value = "true"; fields.Update(); #endregion #region Add attachments if (stage == "end") { // Create the file attachment for this e-mail message. string file = Property.HtmlFileLocation + "/" + Property.ReportZipFileName; if (File.Exists(file) && zipAttch) { message.AddAttachment(file); } else if (!zipAttch) { string htmlFile; if (string.IsNullOrWhiteSpace(reportFileName)) { htmlFile = Property.HtmlFileLocation + "/HtmlReportMail.html"; } else { htmlFile = reportFileName; } message.AddAttachment(htmlFile); } } #endregion if (!string.IsNullOrEmpty(Property.ReportSummaryBody)) { message.HTMLBody = Property.ReportSummaryBody; } else { if (emailStr != null) { string mailTextBody = GetEmailTextBody(emailStr[3], stage); message.TextBody = mailTextBody; } } message.From = "KryptonAutomation"; message.Sender = GetParameter("EmailSMTPUsername").Trim(); message.To = GetRecipientList(); if (emailStr != null) message.Subject = GetEmailSubjectMessage(emailStr[1]); message.Send(); } catch (Exception ex) { Console.WriteLine("Unable to send email notificiation. Error: " + ex.Message + "\n" + "Please make sure you have smtp service installed and running"); } }
/// <summary> /// Mail constructor /// </summary> /// <param name="mailId">Mail ID in database</param> public Mail(int mailId) { _mailId = mailId; var si = new SqlIntegrate(ConnStr); si.AddParameter("@messageid", SqlIntegrate.DataType.Int, mailId); var mailInfo = si.Reader("SELECT * FROM hm_messages WHERE messageid = @messageid"); si.ResetParameter(); si.AddParameter("@messageid", SqlIntegrate.DataType.Int, mailId); Username = si.Query("DECLARE @uid int; SELECT @uid = messageaccountid FROM hm_messages WHERE messageid = @messageid; SELECT accountaddress FROM hm_accounts WHERE accountid = @uid;").ToString().Split('@')[0]; /* The eml file is storage in this way: * * When hmailserver receives an email, it writes information in database and stores the eml file. * * [A] = Hmailserver data path (need to set mailStoragePath in Web.config) * * [B] = Domain name (SAAO.Mail.mailDomain, need to set mailDomainName in Web.config) * * [C] = Username (without domain name, "szhang140" for example) * * [D] = Initial two characters (contain no open brace '{') of eml file name (store in [messagefilename] in database) * * [E] = Eml file name * * [F] = [A] \ [B] \ [C] \ [D] \ [E] ("D:\Mail_Data\xuehuo.org\szhang140\1B\{1B961C98-4FC8-40E3-BC8E-FA5A1D374381}.eml" for example) * * [F] is the absolute path to eml file. */ _emlPath = _mailPath + Username + @"\" + mailInfo["messagefilename"].ToString().Substring(1, 2) + @"\" + mailInfo["messagefilename"]; _message = ReadEml(_emlPath); Flag = (MailFlag)Convert.ToInt32(mailInfo["messageflags"]); Subject = _message.Subject; // Remove '<' and '>' From = new MailAddress( name: _message.From.Split('<')[0].Trim(), mail: _message.From.Split('<')[1].Replace(">", "").Trim() ); var toCount = _message.To.Trim().Split(',').Length; To = new List<MailAddress>(); for (var i = 0; i < toCount; i++) To.Add(new MailAddress( name: _message.To.Split(',')[i].Split('<')[0].Trim(), mail: _message.To.Split(',')[i].Split('<')[1].Replace(">","").Trim() )); SentOn = _message.SentOn; AttachmentCount = _message.Attachments.Count; }
/// <summary> /// CDOMessageSend /// </summary> /// <param name="toEmail"></param> /// <param name="sendusing"></param> /// <returns></returns> public bool CDOMessageSend(string toEmail,int sendusing) { lock (lockHelper) { CDO.Message objMail = new CDO.Message(); try { objMail.To = toEmail; objMail.From = _FromEmail; objMail.Subject = _Subject; if (_Format.Equals(System.Web.Mail.MailFormat.Html)) objMail.HTMLBody = _Body; else objMail.TextBody = _Body; if (!_SmtpPort.Equals("25")) objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = _SmtpPort; //设置端口 objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = _SmtpServer; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = sendusing; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = _FromEmail; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = _FromEmail; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = _SmtpUserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = _SmtpUserName; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = _SmtpPassword; objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1; objMail.Configuration.Fields.Update(); objMail.Send(); return true; } catch { } finally{ } System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail); objMail = null; } return false; }
public static void SaveWebPageToMHTFile2(string url, string filePath) { try { CDO.Message msg = new CDO.Message(); CDO.Configuration cfg = new CDO.Configuration(); msg.Configuration = cfg; // 第一参数为url,第二参数为支持格式,第三参数为用户ID,第四参数为用户密码 msg.CreateMHTMLBody(url, CDO.CdoMHTMLFlags.cdoSuppressAll, "", ""); msg.GetStream().SaveToFile(filePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite); msg = null; //MessageBox.Show("Save OK!!!"); } catch //(Exception ex) { //MessageBox.Show("Error:" + ex.Message); } }
/// <summary> /// Read eml file into CDO message /// </summary> /// <param name="filepath">Path to eml file</param> /// <returns>CDO message</returns> private static CDO.Message ReadEml(string filepath) { var oMsg = new CDO.Message(); var stm = new ADODB.Stream(); stm.Open(System.Reflection.Missing.Value); stm.Type = ADODB.StreamTypeEnum.adTypeBinary; stm.LoadFromFile(filepath); oMsg.DataSource.OpenObject(stm, "_stream"); stm.Close(); return oMsg; }
public MailModel(string mailPath) : base(mailPath) { this.mail = MailHelper.ReadMessage(mailPath); }