static void ProcesarDescarga(string rutaSolicitud) { string json = File.ReadAllText(rutaSolicitud); json = OKHOSTING.Core.Cryptography.SimpleEncryption.Decrypt(json); System.Net.Mail.MailMessage mail; var solicitud = Newtonsoft.Json.JsonConvert.DeserializeObject<SolicitudDescarga>(json); //solicitud.Busqueda = Descargador.TipoBusqueda.Recibidas; //testing Log.Write("ProcesarDescarga", "---------------------NUEVA SOLICITUD : " + rutaSolicitud, Log.Information); Log.Write("ProcesarDescarga", "RFC: " + solicitud.RFC, Log.Information); Log.Write("ProcesarDescarga", "FechaDesde: " + solicitud.FechaDesde, Log.Information); Log.Write("ProcesarDescarga", "FechaHasta: " + solicitud.FechaHasta, Log.Information); Log.Write("ProcesarDescarga", "Busqueda: " + solicitud.Busqueda, Log.Information); Log.Write("ProcesarDescarga", "Email: " + solicitud.Email, Log.Information); string carpeta = Path.Combine(Ruta, "Facturas", Path.GetFileName(rutaSolicitud), solicitud.Busqueda.ToString()); //Descargador.Descargar(solicitud.RFC, solicitud.Contrasena, carpeta, solicitud.FechaDesde, solicitud.FechaHasta, solicitud.Busqueda); try { Descargador.Descargar(solicitud.RFC, solicitud.Contrasena, carpeta, solicitud.FechaDesde, solicitud.FechaHasta, solicitud.Busqueda); } catch (Exception e) { OKHOSTING.Core.Log.Write("ProcesarDescarga", "Error on " + rutaSolicitud + ": " + e, Log.Information); if (e.InnerException != null && e.InnerException.Message.StartsWith("Los datos de acceso son incorrectos")) { //mandar correo mail = new System.Net.Mail.MailMessage(); mail.To.Add(solicitud.Email); mail.Subject = "Tus facturas no pudieron descargarse por contraseña incorrecta"; mail.Body = string.Format("El RFC {0} y contraseña {1} proporcionados no funcionaron, por favor intentalo de nuevo en http://factura.me", solicitud.RFC, solicitud.Contrasena); OKHOSTING.Core.Net.Mail.MailManager.Send(mail); File.Delete(rutaSolicitud); } return; } //exportar a excel List<XmlDocument> facturas = new List<XmlDocument>(); foreach (var f in Directory.GetFiles(carpeta)) { if (!f.EndsWith(".xml")) { continue; } XmlDocument xml = new XmlDocument(); xml.Load(f); facturas.Add(xml); } Exportador.ExportarExcel(facturas, Path.Combine(carpeta, "Facturas.xlsx")); OKHOSTING.Core.Log.Write("ProcesarDescarga", "Excel generado", Log.Information); OKHOSTING.Files.ZipTools.CompressDirectory(carpeta, carpeta + ".zip"); OKHOSTING.Core.Log.Write("ProcesarDescarga", "Zip generado", Log.Information); //mandar correo using (mail = new System.Net.Mail.MailMessage()) using (var att = new System.Net.Mail.Attachment(carpeta + ".zip")) { mail.To.Add(solicitud.Email); mail.Attachments.Add(att); mail.Subject = "Tus facturas estan listas"; mail.Body = string.Format( @"Gracias por usar nuestro servicio, patrocinado por OK HOSTING. RFC: Desde: Hasta: Tipo: ", solicitud.RFC, solicitud.FechaDesde, solicitud.FechaHasta, solicitud.Busqueda); OKHOSTING.Core.Net.Mail.MailManager.Send(mail); OKHOSTING.Core.Log.Write("ProcesarDescarga", "Correo enviado", Log.Information); } File.Delete(rutaSolicitud); //borrar datos if (Directory.Exists(carpeta)) { foreach (string file in Directory.GetFiles(carpeta, "*.*", SearchOption.AllDirectories)) { File.Delete(file); } //Directory.Delete(Path.Combine(Ruta, "Facturas", s.RFC), true); } OKHOSTING.Core.Log.Write("ProcesarDescarga", "Archivos eliminados", Log.Information); }
/// <summary> /// Sends the HTML to the given email addresses. /// </summary> public void SendEmail(string[] toAddresses, string subject, string body, List<string> attachedFilePaths = null) { string fromAddress = emailSenderVisibleAddress; string fromName = emailSenderVisibleName; System.Net.Mail.MailMessage oMsg = new System.Net.Mail.MailMessage(); System.Net.Mail.MailAddress addrFrom = new System.Net.Mail.MailAddress(fromAddress, fromName); oMsg.From = addrFrom; for (int i = 0; i <= toAddresses.Length - 1; i++) { System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(toAddresses[i]); oMsg.To.Add(address); } oMsg.Subject = subject; oMsg.Body = body; //!!! oMsg.IsBodyHtml = true; if (attachedFilePaths != null) { foreach (string path in attachedFilePaths) { System.Net.Mail.Attachment oAttch = new System.Net.Mail.Attachment(path); oMsg.Attachments.Add(oAttch); } } //--- //GENERIC: var client = new System.Net.Mail.SmtpClient(emailSenderHost, emailSenderPort); var myLogin = new System.Net.NetworkCredential(emailSenderUsername, emailSenderPassword); client.EnableSsl = false; client.EnableSsl = false; client.UseDefaultCredentials = true; client.Credentials = myLogin; client.EnableSsl = emailSenderEnableSsl; client.Send(oMsg); }
public static Message ToMessage(this Email email) { Message message = new Message(); var mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress(email.From); mailMessage.To.Add(email.To); mailMessage.ReplyToList.Add(email.From); mailMessage.Subject = email.Subject; mailMessage.Body = email.Body; mailMessage.IsBodyHtml = email.IsHtml; foreach (var attachment in email.Attachments) { System.Net.Mail.Attachment a = new System.Net.Mail.Attachment( new MemoryStream(attachment.File), attachment.Name); mailMessage.Attachments.Add(a); } var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mailMessage); var s = mimeMessage.ToString(); message.Raw = stringToBase64url(mimeMessage.ToString()); return(message); }
public static void SendCsvAttachment(this DataTable dt, string from_address, string to_address, string subject, string body, string smtp_host, string attachment_filename) #endif { // Save this CSV to a string string csv = WriteToString(dt, true); // Prepare the email message and attachment System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(to_address); message.Subject = subject; message.From = new System.Net.Mail.MailAddress(from_address); message.Body = body; System.Net.Mail.Attachment a = System.Net.Mail.Attachment.CreateAttachmentFromString(csv, "text/csv"); a.Name = attachment_filename; message.Attachments.Add(a); // Send the email #if (DOTNET20 || DOTNET35) var smtp = new System.Net.Mail.SmtpClient(smtp_host); smtp.Send(message); #else using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtp_host)) { smtp.Send(message); } #endif }
public ActionResult Email() { MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**"); foreach (string form_inputs in Request.Form.Keys) { String input_name = form_inputs.ToString(); String input_value = Request.Form[form_inputs].Trim(); if (input_name == "File") { HttpPostedFileBase file = Request.Files[input_name]; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(file.InputStream, file.FileName); //ERROR message.Attachments.Add(attachment); } if (input_name == "Name") { message.Body = "Name: " + input_value; } } SmtpClient client = new SmtpClient(); client.Port = 25; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Host = "SMTP.fake.com"; client.Send(message); }
public async static Task CreatePolicy() { IAPIHelper Invoke = new APIHelper(); JObject customerRecord = JObject.Parse(File.ReadAllText(Path.Combine(".", "JsonTemplate", "CreatePolicy.json"))); //TODO customerRecord["customerId"] = CreateCustomer.Instance.CustomerId; customerRecord["policyEffectiveDate"] = CustomerPolicy.Instance.PolicyEffectiveDate; customerRecord["policyExpiryDate"] = CustomerPolicy.Instance.PolicyExpiryDate; customerRecord["paymentOption"] = CustomerPolicy.Instance.PaymentOption; customerRecord["totalAmount"] = CustomerPolicy.Instance.TotalAmount; Option <HttpResponseMessage> getCustomer = await Invoke.PostAPI("https://ai-customer-onboarding-dev.azurewebsites.net/api/Policy", "", HttpStatusCode.Created, customerRecord.ToString()); string getQuoteJson = await getCustomer.Match( None : () => ReportNotFound(), Some : async (r) => await r.Content.ReadAsStringAsync() ); Option <GetCustomer> getCustomerInfo = ConvertToObject <GetCustomer>(getQuoteJson); CreateCustomer.Instance.PolicyNumber = getCustomerInfo.Match( None: () => 0, Some: (c) => Convert.ToInt32(c.PolicyNumber) ); Stream stream = await Invoke.GeneratePdfAsync(CreateCustomer.Instance.CustomerId); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, "policy.pdf"); var emailFlag = EmailService.SendEmail(GetCustomer.Instance.Quote, attachment); }
private void SendLicenseFileEmail(Customer customer, List <IntelliLockManager.License> licenses, string emailTemplateLocation, string attachmentFileName, string emailSubject, string productName) { Dictionary <string, string> templateKeyVals = new Dictionary <string, string>(); templateKeyVals.Add("[customer_name]", customer.FirstName); templateKeyVals.Add("[product_name]", productName); List <System.Net.Mail.Attachment> attachments = new List <System.Net.Mail.Attachment>(); foreach (IntelliLockManager.License license in licenses) { System.Net.Mail.Attachment attachement = new System.Net.Mail.Attachment(new System.IO.MemoryStream(license.LicenseFile), attachmentFileName); attachments.Add(attachement); } EmailManager.Email email = new EmailManager.Email(); email.Attachments = attachments; email.Body = EmailManager.Email.Helper.FormatEmailTemplate(emailTemplateLocation, templateKeyVals); email.FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"]; email.FromHost = ConfigurationManager.AppSettings["FromHost"]; email.FromName = ConfigurationManager.AppSettings["FromName"]; email.FromPort = ConfigurationManager.AppSettings["FromPort"]; email.FromUserName = ConfigurationManager.AppSettings["FromUserName"]; email.FromUserPassword = ConfigurationManager.AppSettings["FromUserPassword"]; email.IsUsingSSL = false; email.Subject = emailSubject; email.ToEmailAddress = customer.Email; EmailManager.EmailManager emailManager = new EmailManager.EmailManager(); emailManager.SendEmail(email); }
private async void Poslji_Click(object sender, RoutedEventArgs e) { try { System.Net.Mail.MailMessage sporočilo = new System.Net.Mail.MailMessage(); sporočilo.Subject = txtZadeva.Text; sporočilo.From = new System.Net.Mail.MailAddress(txtBoxUporabiskoIme.Text); sporočilo.Body = txtBoxVsebinaePoste.Text; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment(txtBoxPriponka.Text); sporočilo.Attachments.Add(attachment); foreach (string za in txtZa.Text.Split(',')) { sporočilo.To.Add(txtZa.Text); } //dovoliš pošiljanje e pošte gmail: https://myaccount.google.com/lesssecureapps //System.Net.Mail.SmtpClient klijent = new System.Net.Mail.SmtpClient("smtp.gmail.com"); System.Net.Mail.SmtpClient klijent = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com"); klijent.Credentials = new System.Net.NetworkCredential(txtBoxUporabiskoIme.Text, pswBoxPassword.Password); klijent.EnableSsl = true; klijent.Port = 587; klijent.Send(sporočilo); await this.ShowMessageAsync("Elektronska pošta", "e-Pošta je uspešno poslana.", MessageDialogStyle.Affirmative); } catch (Exception ex) { await this.ShowMessageAsync("Napaka", ex.Message, MessageDialogStyle.Affirmative); } }
public static void Send(string message, string subject, string to, string from, string login, int port, string smtpHost, string password, string attachment) { try { System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); mail.To.Add(to); mail.From = new System.Net.Mail.MailAddress(from); mail.Subject = subject; string Body = message; mail.Body = Body; if (attachment != null) { System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(attachment); mail.Attachments.Add(at); } mail.IsBodyHtml = true; using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpHost, port)) { //smtp.Host = smtpHost; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential (from, password); //Or your Smtp Email ID and Password smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.EnableSsl = true; smtp.Send(mail); } } catch (Exception ex) { //TODO return the error throw new Exception(string.Format("FAILED send email error [{0}] [{1}]", ex.Message, ex.InnerException.Message)); } }
static void WriteCsirtMail() { string attachFile = Directory.GetCurrentDirectory() + "\\results.txt"; var resultStr = header + "<br/>" + String.Join("",vtApi.results.Select(ss => ss.ToString() + " <br/>")); //File.ReadAllText(attachFile).Replace("\r\n", "<p></p>").Replace("\t", "	"); OutlookApp outlookApp = new OutlookApp(); MailItem mailItem = outlookApp.CreateItem(OlItemType.olMailItem); mailItem.Importance = OlImportance.olImportanceHigh; mailItem.Subject = "Hash Engellenmesi Hk."; // "pre" tag is standing for render as it is dont change anything, thats why we cannot tab on there mailItem.HTMLBody = "<pre " + "style=\"font-family:'consolas'\" >" + @"Merhaba,<br/> Aşağıdaki -McAffee Detected?- değeri False ve NotInDB olan <strong>MD5 HASH'lerin engellenmesi</strong> ATAR sistemi üzerinden yapılmıştır.<br/> Syg.<br/> " + resultStr + "</pre>"; mailItem.To = speconfig.csirtMail; mailItem.CC = speconfig.ksdestekMail; if (!File.Exists(attachFile)) Console.Write("\nAttached document " + attachFile + " does not exist", Color.Red); else { System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(attachFile); mailItem.Attachments.Add(attachFile, OlAttachmentType.olByValue, Type.Missing, Type.Missing); } mailItem.Display(); }
public static void enviarMail(string nomeDe, string passwordDe, string paraQuem, string assunto, string texto, string anexo = null) { //objetos email System.Net.Mail.MailMessage mensagem = new System.Net.Mail.MailMessage(); System.Net.NetworkCredential credenciais = new System.Net.NetworkCredential(nomeDe, passwordDe); System.Net.Mail.MailAddress deQuem = new System.Net.Mail.MailAddress(nomeDe); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); //mensagem mensagem.To.Add(paraQuem); mensagem.From = deQuem; mensagem.Subject = assunto; mensagem.Body = texto; mensagem.IsBodyHtml = true; //servidor smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = credenciais; //anexo if (anexo != null && anexo != "") { if (System.IO.File.Exists(anexo) == true) { System.Net.Mail.Attachment ficheiroAnexo = new System.Net.Mail.Attachment(anexo); mensagem.Attachments.Add(ficheiroAnexo); } } //enviar smtp.Send(mensagem); }
private void btnGrabScreen_Click(object sender, EventArgs e) { try { //lstEmail.Visible = false; i = i + 1; //string sysName = string.Empty; //string sysUser = string.Empty; Bitmap b = BitMapCreater(); printScreen = string.Format("{0}{1}", Path.GetTempPath(), "screen" + i + ".jpg"); b.Save(printScreen, ImageFormat.Jpeg); picScreenCapture.Load(printScreen.ToString()); System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("*****@*****.**"); System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("*****@*****.**"); System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress); // sysName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); // sysUser = System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString(); mm.Subject = "unsubscribe"; string filename = string.Empty; System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(printScreen); mm.Attachments.Add(mailAttachment); mm.IsBodyHtml = true; mm.BodyEncoding = System.Text.Encoding.UTF8; sendMail(mm); } catch (Exception ex) { } }
public static void SubmitForm(Panel FormPanel, Panel CompletionPanel, string from, string to, string sub, HttpFileCollection fileCollection = null) { FormPanel.Visible = false; string br = "\n"; string msg = ""; foreach (Control ctrl in FormPanel.Controls) { msg += getMessage(ctrl); } if (fileCollection != null && fileCollection.Count > 0) { List <System.Net.Mail.Attachment> attachments = new List <System.Net.Mail.Attachment>(); for (int i = 0; i < fileCollection.Count; i++) { System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(fileCollection[i].InputStream, fileCollection[i].FileName, fileCollection[i].ContentType); System.Net.Mime.ContentDisposition cd = a.ContentDisposition; cd.FileName = fileCollection[i].FileName; attachments.Add(a); } Util.sendEmail(to, sub, msg, from, attachments, false); } else { Util.sendEmail(to, sub, msg, from, null, false); } msg += "From: " + from + br; msg += "To: " + to + br; msg += "Subject: " + sub + br; CompletionPanel.Visible = true; }
public static void SendMail(string emailsTo, string subject, string body, string strAttachPath) { if (!string.IsNullOrEmpty(emailsTo)) { System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(); System.Net.Mail.Attachment attach = null; // compose the email message email.IsBodyHtml = true; email.From = new System.Net.Mail.MailAddress("\"Autoccasion Last Cars\" <" + SmtpConnection.SmtpFrom + ">"); int i = 0; foreach (var emailAddress in emailsTo.Split(Convert.ToChar(";")).ToList()) { if (emailAddress.IndexOf("@") > 0) email.To.Add(emailAddress.Trim()); } email.Subject = subject; email.Body = body; if (strAttachPath.Length > 0) { attach = new System.Net.Mail.Attachment(strAttachPath); email.Attachments.Add(attach); } var client = new System.Net.Mail.SmtpClient(SmtpConnection.SmtpServer, SmtpConnection.SmtpPort) { EnableSsl = SmtpConnection.SmptUseSSL }; if ((SmtpConnection.SmtpUser.Length > 0) & (SmtpConnection.SmtpPass.Length > 0)) client.Credentials = new System.Net.NetworkCredential(SmtpConnection.SmtpUser, SmtpConnection.SmtpPass); // send the email client.Send(email); } }
private static void SendMail(string _mailTo, System.IO.MemoryStream ms) { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(_mailTo); message.Subject = "Monitoring Alert"; message.From = new System.Net.Mail.MailAddress(senderAccount); message.Body = "Production monitoring produced candidates to review. Please see attached."; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); attach.ContentDisposition.FileName = $"MonitoringResults.txt"; message.Attachments.Add(attach); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer) { Port = 587, UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(senderAccount, senderSecret), EnableSsl = true }; smtp.Send(message); }
public bool SendEmail(string toAddress, string subject, string body, string attachmentPath) { bool bRtn = true; string fromAddress = "*****@*****.**"; string userName = GlobalVariables.SendEmailUserName; string userPassword = GlobalVariables.SendEmailUserPassword; string smtpClient = "smtp.gmail.com"; //string attachmentpath = attachmentPath; try { System.Net.Mail.MailAddress SendFrom = new System.Net.Mail.MailAddress(fromAddress); System.Net.Mail.MailAddress SendTo = new System.Net.Mail.MailAddress(toAddress); System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage(SendFrom, SendTo); MyMessage.Subject = subject; MyMessage.Body = body; System.Net.Mail.Attachment attachFile = new System.Net.Mail.Attachment(attachmentPath); MyMessage.Attachments.Add(attachFile); System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient(smtpClient); emailClient.Credentials = new System.Net.NetworkCredential(userName, userPassword); emailClient.Port = 587; emailClient.EnableSsl = true; emailClient.Send(MyMessage); } catch (Exception ex) { Log.Error(ex); bRtn = false; } return(bRtn); }
protected void btnsend_Click(object sender, EventArgs e) { System.Net.Mail.Attachment attachFile = null; string strmdetail = "<table cellpadding='4' cellspacing='0' width='700' align='center' style='border:solid 1px #e0e0e0;'><tr><td style='border:solid 1px #e0e0e0;' width='100'>Sender Email:</td><td style='border:solid 1px #e0e0e0;'>" + txtemail.Text + "</td></tr><tr><td style='border:solid 1px #e0e0e0;vertical-align:top;' width='100' valign='top'>Message:</td><td style='border:solid 1px #e0e0e0;vertical-align:top;' height='400' valign='top'>" + txtcomment.Text + "</td></tr>"; string msg = ""; objda.action = "select"; objda.id = "1"; if (ds.Tables[0].Rows.Count > 0) { msg = objda.SendEmail("*****@*****.**" + ",", "Support Message on QuickStart", strmdetail, "", "", ""); } if (msg == "Sent") { error.InnerText = "Your email sent successfully to Administrator."; blank(); diverror.Visible = true; diverror1.Visible = false; } else { error1.InnerText = "Error in sending email, please try again"; diverror1.Visible = true; diverror.Visible = false; } }
public void SendMail(string email, string fromMail, string fromName, string passMail, string subject, string strBody, List <string> lstAttachFile) { System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress(fromMail, fromName), new System.Net.Mail.MailAddress(email)); m.Subject = subject; m.Body = strBody; m.IsBodyHtml = true; if (lstAttachFile != null) { System.Net.Mail.Attachment attachment; foreach (var attachFile in lstAttachFile) { attachment = new System.Net.Mail.Attachment(attachFile); m.Attachments.Add(attachment); } } System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com"); smtp.Credentials = new System.Net.NetworkCredential(fromMail, passMail); smtp.EnableSsl = true; smtp.Send(m); }
/// <summary> /// 发送邮件 /// MailMsg msg= new MailMsg(); /// msg.Subject="";... /// Smtp smtp = new Smtp("mail.OpenSmtp.com", 25); /// smtp.Username=""; /// smtp.Password=""; /// smtp.SendMail(msg); /// </summary> /// <param name="msg"></param> public void SendMail(MailMsg msg) { System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(msg.From); System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(msg.To); //System.Net.Mail.MailAddress copyTo = new System.Net.Mail.MailAddress(model.CopyTo); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to); message.Subject = msg.Subject; message.Body = msg.Body; message.SubjectEncoding = System.Text.Encoding.UTF8; message.BodyEncoding = System.Text.Encoding.UTF8; if (msg.AttachmentList != null && msg.AttachmentList.Count > 0) { foreach (String attachment in msg.AttachmentList) { if (File.Exists(attachment)) { System.Net.Mail.Attachment attachFile = new System.Net.Mail.Attachment(attachment); message.Attachments.Add(attachFile); } } } System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(this.Host); client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(this.Username, this.Password); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.Send(message); message.Dispose(); }
public void SendInvoiceMail(string to, BillViewModel model, FileStreamResult invoice) { var nameFrom = _configuration["Mail:NameFrom"]; var from = _configuration["Mail:From"]; var smtp = _configuration["Mail:Smtp"]; var port = _configuration["Mail:Port"]; var password = _configuration["Mail:Password"]; var message = new MimeMessage(); message.From.Add(new MailboxAddress(nameFrom, from)); message.To.Add(new MailboxAddress(to, to)); message.Subject = "Ricardo's Water Company Invoice"; System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(invoice.FileStream, invoice.ContentType); var bodyBuilder = new BodyBuilder { TextBody = $"Invoice n.{model.Id} for the following date: {model.MonthYear}" }; bodyBuilder.Attachments.Add(invoice.FileDownloadName, file.ContentStream); message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { client.Connect(smtp, int.Parse(port), false); client.Authenticate(from, password); client.Send(message); client.Disconnect(true); } }
/// <summary> /// 发送邮件函数 /// </summary> /// <param name="SmtpServer">smtp服务器 比如:"smtp.163.com"</param> /// <param name="PortNo">smtp服务器端口号: 默认 25</param> /// <param name="UserName">smtp服务器用户名 比如:zhaoxianfa</param> /// <param name="PassWord">smtp服务器用户密码: 比如: xxxxx</param> /// <param name="Sender">发件人邮箱地址 比如:[email protected]</param> /// <param name="Receiver">收件人邮箱地址 比如: [email protected]</param> /// <param name="Subject">邮件标题 比如: 本月工资条 </param> /// <param name="Content">邮件内容 比如: 实发工资20000</param> /// <param name="FileList">发送文件列表 内容为文件的服务器物理绝对路径</param> /// <returns>成功返回true,否则返回false</returns> public static bool SendMail(string SmtpServer, int PortNo, string UserName, string PassWord, string Sender, string Receiver, string Subject, string Content, System.Collections.Generic.List <string> FileList) { try { System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage(); myMail = new System.Net.Mail.MailMessage(Sender, Receiver, Subject, Content); if (FileList != null) { for (int i = 0; i < FileList.Count; i++) { string file = FileList[i].ToString(); System.Net.Mail.Attachment myAttachment = new System.Net.Mail.Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet); System.Net.Mime.ContentDisposition disposition = myAttachment.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); myMail.Attachments.Add(myAttachment); } } System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(SmtpServer, PortNo); client.Credentials = new System.Net.NetworkCredential(UserName, PassWord); client.Send(myMail); return(true); } catch { return(false); } }
static void SaveAttachmentToDisk(System.Net.Mail.Attachment attachment) { using (var fileStream = File.Create("C:\\_tmp\\imap\\" + attachment.Name)) { attachment.ContentStream.Seek(0, SeekOrigin.Begin); attachment.ContentStream.CopyTo(fileStream); } }
private void sendEmail() { if (textBoxFrom.Text.Equals("")) { MessageBox.Show("From empty!"); return; } buttonSend.Text = "Sending..."; this.Cursor = System.Windows.Forms.Cursors.WaitCursor; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.From = new System.Net.Mail.MailAddress("*****@*****.**"); message.To.Add("*****@*****.**"); //message.To.Add("*****@*****.**"); //message.To.Add("*****@*****.**"); //message.To.Add("*****@*****.**"); message.To.Add("*****@*****.**"); message.Subject = "[beSmart] Report Error/Suggestion"; try { System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(textBoxAttach.Text); message.Attachments.Add(attach); } catch (Exception) { } string body = "FROM: " + textBoxFrom.Text; body += "SUBJECT: " + textBoxSubject.Text; body += "\n\n_____________________________________________________\n\n"; body += richTextBoxBody.Text; message.Body = body; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "li4grupo13"); try { smtp.Timeout = 15; smtp.Send(message); this.Cursor = System.Windows.Forms.Cursors.Default; MessageBox.Show("Send!"); } catch (Exception e) { this.Cursor = System.Windows.Forms.Cursors.Default; MessageBox.Show(e.Message); } this.Cursor = System.Windows.Forms.Cursors.Default; buttonSend.Text = "Send"; }
private void button4_Click(object sender, EventArgs e) { //メッセージボックスを表示する DialogResult result = MessageBox.Show("メールを送信しますか?", "写真メール送信", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); // ダイアログでOKを押したときだけ送信処理 if (result == DialogResult.Yes) { //MailMessageの作成 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); //送信者 msg.From = new System.Net.Mail.MailAddress(myMailAddress); //宛先 msg.To.Add(new System.Net.Mail.MailAddress(toMailAddress)); //.NET Framework 3.5以前では、以下のようにする //msg.ReplyTo = new System.Net.Mail.MailAddress("*****@*****.**"); //Sender //msg.Sender = new System.Net.Mail.MailAddress("*****@*****.**"); //件名 msg.Subject = "こんにちは"; //本文 msg.Body = toMailMessage; //メールの配達が遅れたとき、失敗したとき、正常に配達されたときに通知する msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.Delay | System.Net.Mail.DeliveryNotificationOptions.OnFailure | System.Net.Mail.DeliveryNotificationOptions.OnSuccess; //画像をファイルで添付する System.Net.Mail.Attachment attach1 = new System.Net.Mail.Attachment("Image.jpg"); //動画の場合 //System.Net.Mail.Attachment attach1 = new System.Net.Mail.Attachment("anoto.avi"); msg.Attachments.Add(attach1); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(); //SMTPサーバーなどを設定する sc.Host = myMailServer; sc.Port = 587; //GMail認証 sc.Credentials = new System.Net.NetworkCredential(myMailID, myMailPassword); //SSL sc.EnableSsl = true; sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //メッセージを送信する sc.Send(msg); //後始末 msg.Dispose(); //後始末(.NET Framework 4.0以降) sc.Dispose(); } }
public void Add(System.Net.Mail.Attachment attachment) { base.Add(new MailMessageAttachment { Content = attachment.ContentStream.ToByteArray(), ContentType = attachment.ContentType.MediaType, Name = attachment.Name }); }
/// <summary> /// Converts this to a System.Net.Mail.Attachment. /// </summary> internal System.Net.Mail.Attachment ToAttachment() { if( stream == null ) return new System.Net.Mail.Attachment( filePath ); var attachment = new System.Net.Mail.Attachment( stream, contentType ); attachment.ContentDisposition.FileName = attachmentDisplayName; return attachment; }
private bool SendMail(string strTo, string strBody, string strSubject, List <string> lstsAttachmens) { try { System.Net.Mail.MailMessage oMailMessage = new System.Net.Mail.MailMessage(); oMailMessage.IsBodyHtml = true; oMailMessage.Priority = System.Net.Mail.MailPriority.Normal; oMailMessage.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure; System.Net.Mail.MailAddress oMailAddress = null; string strMail = textBox2.Text; string strName = textBox1.Text; oMailAddress = new System.Net.Mail.MailAddress(strMail, strName); //oMailAddress.DisplayName = "Mehdi Ejazi"; oMailMessage.From = oMailAddress; oMailMessage.Sender = oMailAddress; //oMailMessage.ReplyTo = oMailAddress; oMailAddress = new System.Net.Mail.MailAddress(strTo); //oMailAddress.DisplayName = "Job Resume"; oMailMessage.To.Add(oMailAddress); oMailMessage.SubjectEncoding = System.Text.Encoding.UTF8; oMailMessage.Subject = strSubject; oMailMessage.BodyEncoding = System.Text.Encoding.UTF8; oMailMessage.Body = strBody; foreach (string strAttFile in lstsAttachmens) { System.Net.Mail.Attachment oAttachment = new System.Net.Mail.Attachment(strAttFile); oMailMessage.Attachments.Add(oAttachment); } System.Net.Mail.SmtpClient oStmpClient = new System.Net.Mail.SmtpClient(); oStmpClient.EnableSsl = true; oStmpClient.Timeout = 180000; //oStmpClient.Host; //oStmpClient.Port; //mailer.Host = "mail.youroutgoingsmtpserver.com"; //mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword"); oStmpClient.Send(oMailMessage); return(true); } catch { return(false); } }
/// <summary> /// Sends an email with fewer options. SMTP server info comes from Web.config. /// </summary> /// <param name="strFrom">The from field. Required.</param> /// <param name="strTo">Recipients. Separate with comma. Required.</param> /// <param name="strCC">CC recipients. Separate with comma. Optional; use null or Nothing if blank.</param> /// <param name="strAttachments">Attachments. Separate with comma. Optional; use null or Nothing if blank.</param> /// <param name="strSubject">The subject of the message. Required.</param> /// <param name="strBody">The body of the message. Required.</param> /// <returns>Retuns success or exception.</returns> public string SendEmail(string strFrom, string strTo, string strCC, string strAttachments, string strSubject, string strBody) { // Create string to hold success message. string strEmailSuccess = String.Empty; try { using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage()) { msg.IsBodyHtml = false; msg.From = new System.Net.Mail.MailAddress(strFrom); // Split the To string into an array and add each address. string[] strToArray = strTo.Split(','); foreach (string strToRecipient in strToArray) { msg.To.Add(new System.Net.Mail.MailAddress(strToRecipient)); } if ((strCC != null) && (strCC != String.Empty) && (strCC.Length > 0)) { // Split the CC string into an array and add each address. string[] strCCArray = strCC.Split(','); foreach (string strCCRecipient in strCCArray) { msg.CC.Add(new System.Net.Mail.MailAddress(strCCRecipient)); } } msg.Subject = strSubject; msg.Body = strBody; if ((strAttachments != null) && (strAttachments != String.Empty) && (strAttachments.Length > 0)) { // Split the attachments string into an array and add each attachment. string[] strAttachmentArray = strAttachments.Split(','); foreach (string strAttachment in strAttachmentArray) { System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(strAttachment); msg.Attachments.Add(attachment); } } using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(System.Web.Configuration.WebConfigurationManager.AppSettings["GlobalSMTP"].ToString())) { System.Net.NetworkCredential user = new System.Net.NetworkCredential(System.Web.Configuration.WebConfigurationManager.AppSettings["GlobalSMTPUser"].ToString(), System.Web.Configuration.WebConfigurationManager.AppSettings["GlobalSMTPPass"].ToString()); client.Credentials = user; client.EnableSsl = true; client.Send(msg); } strEmailSuccess = "Simple overload sent at " + System.DateTime.Now.ToString() + "!"; } } catch (Exception ex) { strEmailSuccess = ex.ToString(); } return(strEmailSuccess); }
/// <summary> /// /// </summary> /// <param name="rows"></param> static public void WriteSomeMail(List <Result> results) { var resultTable = "NA"; var cellProperty = @"<td width=130 nowrap valign=bottom style='width:97.75pt;border:none;height:15.0pt'> <p class=MsoNormal><span style='font-family:Calibri;mso-fareast-language:TR'>"; var cellEnd = @"<o:p></o:p></span></p></td>"; try { //string headerSpan = @"<p class=MsoNormal><span style='font-size:12.0pt;font-family:Consolas;color:blue;mso-fareast-language:TR'>"; string tableHeader = "TABLE HEADER"; //Resources.tableHeader.Replace("01.08.19 - 11:07", DateTime.Now.ToString("dd/MM/yy - HH:mm")); List <string> excelRows = new List <string>(); foreach (Result result in results) { var rowData = ""; result.ToArray().ToList().ForEach(rr => rowData += cellProperty + rr + cellEnd); excelRows.Add("<tr style='mso-yfti-irow:2;height:15.0pt'> " + rowData + "</tr>"); // a table raw created } resultTable = tableHeader + String.Join("", excelRows) + "</table>"; // end of the creating table } catch (System.Exception ee) { Console.Write("\n Creating table for mailing is failed . . . ", Color.Red); Console.Write("\n Exception: " + ee.Message, Color.Orange); resultTable = "No Table Created"; } Outlook.Application OutApp = new Outlook.Application(); MailItem mailItem = (MailItem)OutApp.CreateItem(OlItemType.olMailItem); mailItem.Importance = OlImportance.olImportanceHigh; mailItem.Subject = "Scanning IP Addresses"; // "pre" tag is standing for render as it is dont change anything, thats why we cannot tab on there mailItem.HTMLBody = "<pre " + "style=\"font-family:'Arial TUR'\" >" + @"Merhaba,<br/> Ekteki Scanning IP raporlarına istinaden aşağıdaki <strong style='color:red;'>kırmızı olmayan IP'lerin</strong> erişimi blissadmin ile kesilmiştir.<br/> Syg.<br/><br/>" + resultTable + "</pre>"; mailItem.To = MainClass.speconfig.csirtMail + "," + MainClass.speconfig.altyapiMail; //mailItem.CC = MainClass.speconfig.atarMail; var attachFiles = Directory.GetFiles(Directory.GetCurrentDirectory()). Where(ff => ff.Contains("Scanning IP Addresses") || ff.Contains("Acunn666")).ToList(); if (attachFiles.Where(ff => !File.Exists(ff)).Count() > 0) { Console.Write("\nSome of the Attached documents( " + String.Join(",", attachFiles.Where(ff => !File.Exists(ff))) + " ) are missing", Color.Red); } else { System.Net.Mail.Attachment attachment; foreach (string att in attachFiles) { attachment = new System.Net.Mail.Attachment(att); mailItem.Attachments.Add(att, OlAttachmentType.olByValue, Type.Missing, Type.Missing); } } mailItem.Display(); }
public ActionResult Create(InvitationViewModel invitation) { if (ModelState.IsValid) { var org = db.Organizations.Find(invitation.OrganizationId); List <Invitation> invites = new List <Invitation>(); foreach (var email in invitation.Emails.Split('\n')) { Invitation invite = new Invitation() { CreatedDate = DateTimeOffset.Now, Email = email.Trim(), SalesPersonEmail = invitation.SalesPersonEmail, Company = org.Name, OrganizationId = invitation.OrganizationId, Type = invitation.Type }; invites.Add(invite); db.Invitations.Add(invite); } int count = db.SaveChanges(); AddSuccess($"{count} invitations created."); // set the invite request to granted var request = db.InvitationRequests.Find(invitation.RequestId); if (request != null) { request.Status = RequestStatus.Granted; db.SaveChanges(); } if (count > 0) { IUserMailer UserMailer = new UserMailer(); foreach (var i in invites) { try { System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(Server.MapPath("~/Content/VaworksInstructions.pdf")); Mvc.Mailer.MvcMailMessage msg = UserMailer.Invitation(i); msg.Attachments.Add(at); msg.Send(); } catch (Exception ex) { return(View("MailDown", ex)); } } } return(Confirmation()); } PopulateDropDown(invitation.OrganizationId); return(View(invitation)); }
/// <summary> /// Converts this to a System.Net.Mail.Attachment. /// </summary> internal System.Net.Mail.Attachment ToAttachment() { if (Stream == null) { return(new System.Net.Mail.Attachment(FilePath)); } var attachment = new System.Net.Mail.Attachment(Stream, contentType); attachment.ContentDisposition.FileName = AttachmentDisplayName; return(attachment); }
public static void EmailMessage(string strSubject, string strMessage, bool blnInternalEmail = true, string strAttachementPath = "", bool isBodyHTML = false) { //************************************************************************** //Written By: Pamela Alford //Date: 08/10/06 //Edited 12/3/13 By: David Gates //Reason: Pickup folder no longer exists changed code to implement a new method //*************************************************************************** try { string[] Toemail = new string[] { }; if (blnInternalEmail == true) { Toemail = Conf.GetString("InternalEmail", "[email protected], [email protected]").Split(','); //Toemail = Conf.GetString("InternalEmail", "[email protected], [email protected]").Split(','); } else { Toemail = Conf.GetString("ExternalEmail", "[email protected],[email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]").Split(','); } AutoEmail.EmailClass Email = new AutoEmail.EmailClass(); if (strAttachementPath != "") { System.Net.Mail.Attachment File = new System.Net.Mail.Attachment(strAttachementPath); System.Net.Mail.Attachment[] AttachmentLetterReport = new System.Net.Mail.Attachment[] { File }; Email.SendEmailtoContacts(strSubject, strMessage, "*****@*****.**", Toemail, "ReportsApplication1", AttachmentLetterReport, isBodyHTML); } else { Email.SendEmailtoContacts(strSubject, strMessage, "*****@*****.**", Toemail, "ReportsApplication1", null, isBodyHTML); } } catch (Exception ex) { //WriteToLogFile(ex.ToString); //MsgBox(ex.ToString) string s = string.Format("EmailMessage Error: {0}", ex.Message); Log.Error(s); if (ex.InnerException != null) { string inner = string.Format("InnerException: {0}", ex.InnerException.Message); Log.Error(inner); } } }
public static string Send_Email_With_BCC_Attachment(string SendTo, string SendBCC, string SendFrom, string Subject, string Body, string AttachmentPath) { try { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); string from = SendFrom; string to = SendTo; //Danh sách email được ngăn cách nhau bởi dấu ";" string subject = Subject; string body = Body; string bcc = SendBCC; bool result = true; String[] ALL_EMAILS = to.Split(';'); foreach (string emailaddress in ALL_EMAILS) { result = regex.IsMatch(emailaddress); if (result == false) { return("Địa chỉ email không hợp lệ."); } } if (result == true) { try { System.Net.Mail.MailMessage em = new System.Net.Mail.MailMessage(from, to, subject, body); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(AttachmentPath); em.Attachments.Add(attach); em.Bcc.Add(bcc); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com";//Ví dụ xử dụng SMTP của gmail smtp.Send(em); return(""); } catch (Exception ex) { return(ex.Message); } } else { return(""); } } catch (Exception ex) { return(ex.Message); } }
private static bool SendEmailUsingSMTP(string from, string to, List <string> cc, List <string> bcc, byte[] attach, string attachFileName, string mailServer, string Port, string smtpUser, string smtpUserPwd, string subj, string body) { //************** IF NOT SENDGRID, SEND USING LOCAL SMTP SERVER ****** System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.Subject = subj; message.Body = body; message.IsBodyHtml = true; message.From = new System.Net.Mail.MailAddress(from); message.To.Add(to); if (cc != null) { foreach (string cc1 in cc) { message.CC.Add(cc1); } } if (bcc != null) { foreach (string bcc1 in bcc) { message.Bcc.Add(bcc1); } } //*************ATTACHMENT START************************** if (attach != null) { System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(new MemoryStream(attach), attachFileName); message.Attachments.Add(att); } //*************ATTACHMENT END**************************** //***************SET SMTP SERVER ************************* if (smtpUser.Length > 0) //smtp server requires authentication { var smtp = new System.Net.Mail.SmtpClient(mailServer, Convert.ToInt32(Port)) { Credentials = new System.Net.NetworkCredential(smtpUser, smtpUserPwd), EnableSsl = true }; smtp.Send(message); } else { System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(mailServer); smtp.Send(message); } return(true); }
public void SaveMailAttachment(System.Net.Mail.Attachment attachment) { byte[] allBytes = new byte[attachment.ContentStream.Length]; int bytesRead = attachment.ContentStream.Read(allBytes, 0, (int)attachment.ContentStream.Length); //save files in attchments folder string destinationFile = @"c:\tmp\" + attachment.Name; BinaryWriter writer = new BinaryWriter(new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); writer.Write(allBytes); writer.Close(); }
public void SendMail(string message, string subject, string to, bool isHtml, byte[] attachment = null, EmailTemplates template = EmailTemplates.None) { if (attachment != null) { var attachData = new System.Net.Mail.Attachment(new MemoryStream(attachment), ""); } if (message.Trim() == "" || subject.Trim() == "" || to.Trim() == "") { throw new System.Net.Mail.SmtpException("Invalid data passed into the FakeEmail class"); } }
private static void OnChange(object source, FileSystemEventArgs e) { try { string filePath = e.FullPath; List<string> parentDirs = filePath.Split('\\').ToList(); string userName = parentDirs[7].ToString(); //This is the directory we are monitoring for change. DirectoryInfo info = new DirectoryInfo(@"C:\Program Files (x86)\Avaya\IP Office\Voicemail Pro\VM\Accounts\" + userName); userName = userName.Replace(" ", "."); Thread.Sleep(1000); string email = "Your Email"; string emailPassword = "******"; List<FileInfo> files = info.GetFiles().OrderByDescending(p => p.CreationTime).ToList(); string wavPath = files[0].DirectoryName + "\\" + files[0].ToString(); string date = DateTime.Now.ToString(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); System.Net.Mail.Attachment mail = new System.Net.Mail.Attachment(wavPath); //Creating message body message.Subject = "A new voicemail has been recieved at: " + date; message.Attachments.Add(mail); message.To.Add(userName); message.From = new System.Net.Mail.MailAddress(email); message.Body = "You have recieved a new voicemail. Please see the attached document and have a great day!"; //setting up SMTP client to be used, in this case basic google. System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com"); smtp.Port = 25; smtp.Credentials = new System.Net.NetworkCredential(email, emailPassword); smtp.EnableSsl = true; smtp.Send(message); //A simple console log for the viewers pleasure. Console.WriteLine("An email has been sent to " + userName); //diposing of objects message.Dispose(); mail.Dispose(); smtp.Dispose(); } catch { //if any errors can view log to see which error was caught using (StreamWriter writer = new StreamWriter(@"C:\EmailSentErrors\ErrorDoc.txt", true)) { writer.WriteLine("Error sending email on " + DateTime.Now.ToString()); writer.WriteLine("------------------------------------------"); } } }
public virtual MvcMailMessage Success(MessageModel model) { ViewData.Model = model; System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(model.FileName); attachment.ContentType = new System.Net.Mime.ContentType("text/calendar"); return Populate(x => { x.Subject = model.Subject; x.ViewName = "Success"; x.Attachments.Add(attachment); x.To.Add(model.Email); }); }
//called within CheckEmailSend, sends email with the appropriate data private void sendEmailUpdate(double curTime, int events) { //send Counter, timeElapsed, video? try { emailCounter++; System.Net.NetworkCredential cred = new System.Net.NetworkCredential(sender, password); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(recipient); //can add multiple recipients by duplicating message.To.Add(recipient) line message.From = new System.Net.Mail.MailAddress(sender); message.Subject = "Update" + DateTime.Today.Date + emailCounter.ToString(); message.Body = "Number of Events Completed: " + events.ToString() + "\n" + "Time Elapsed: " + curTime.ToString() + "\n"; //can attach data to the email (such as the movement value file demonstrated below) System.Net.Mail.Attachment data = null; if(sendData){ data = new System.Net.Mail.Attachment(fileHandler.getMovementFileName()); message.Attachments.Add(data);} //Change the client if not using gmail System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com"); client.Credentials = cred; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Port = 587; //send the email client.Send(message); if (sendData && data !=null) { data.Dispose(); } } catch { Console.WriteLine("unable to send email from " + sender); if (sender == "") { Console.WriteLine("no sender provided for email"); } } }
///<summary> /// 添加附件 ///</summary> ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param> public void AddAttachments(string attachmentsPath) { try { string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义 System.Net.Mail.Attachment data; System.Net.Mime.ContentDisposition disposition; for (int i = 0; i < path.Length; i++) { data = new System.Net.Mail.Attachment(path[i], System.Net.Mime.MediaTypeNames.Application.Octet); disposition = data.ContentDisposition; disposition.CreationDate = File.GetCreationTime(path[i]); disposition.ModificationDate = File.GetLastWriteTime(path[i]); disposition.ReadDate = File.GetLastAccessTime(path[i]); mMailMessage.Attachments.Add(data); } } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey( "Software", true); key.CreateSubKey("sendmail"); key = key.OpenSubKey("sendmail", true); key.CreateSubKey("1"); key = key.OpenSubKey("1", true); if( args.Length < 1 ) { System.Console.WriteLine( "Expected at least 1 command line argument"); return; } if (args[0].Equals("set", System.StringComparison.OrdinalIgnoreCase)) { if (args.Length < 3) { System.Console.WriteLine( "Expected at least 3 command line arguments"); return; } if (args[1].Equals( "smtp", System.StringComparison.OrdinalIgnoreCase)) { key.SetValue("smtp", args[2]); System.Console.WriteLine("Done"); } else if (args[1].Equals( "port", System.StringComparison.OrdinalIgnoreCase)) { key.SetValue("port", args[2]); System.Console.WriteLine("Done"); } else if (args[1].Equals( "to", System.StringComparison.OrdinalIgnoreCase)) { key.SetValue("to", args[2]); System.Console.WriteLine("Done"); } else if (args[1].Equals( "from", System.StringComparison.OrdinalIgnoreCase)) { key.SetValue("from", args[2]); System.Console.WriteLine("Done"); } else if (args[1].Equals( "userid", System.StringComparison.OrdinalIgnoreCase)) { key.SetValue("userid", args[2]); System.Console.WriteLine("Done"); } else { System.Console.WriteLine("Don't know what to set"); } return; } else if (args[0].Equals( "get", System.StringComparison.OrdinalIgnoreCase)) { if (args.Length < 2) { System.Console.WriteLine( "Expected at least 2 command line arguments"); return; } if (args[1].Equals( "smtp", System.StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine(key.GetValue("smtp")); } else if (args[1].Equals( "port", System.StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine(key.GetValue("port")); } else if (args[1].Equals( "to", System.StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine(key.GetValue("to")); } else if (args[1].Equals( "from", System.StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine(key.GetValue("from")); } else if (args[1].Equals( "userid", System.StringComparison.OrdinalIgnoreCase)) { System.Console.WriteLine(key.GetValue("userid")); } else { System.Console.WriteLine("Don't know what to get"); } return; } else if (args[0].Equals( "clear", System.StringComparison.OrdinalIgnoreCase)) { if (args.Length < 2) { System.Console.WriteLine( "Expected at least 2 command line arguments"); return; } if (args[1].Equals( "smtp", System.StringComparison.OrdinalIgnoreCase)) { key.DeleteValue("smtp"); System.Console.WriteLine("Done"); } else if (args[1].Equals( "port", System.StringComparison.OrdinalIgnoreCase)) { key.DeleteValue("port"); System.Console.WriteLine("Done"); } else if (args[1].Equals( "to", System.StringComparison.OrdinalIgnoreCase)) { key.DeleteValue("to"); System.Console.WriteLine("Done"); } else if (args[1].Equals( "from", System.StringComparison.OrdinalIgnoreCase)) { key.DeleteValue("from"); System.Console.WriteLine("Done"); } else if (args[1].Equals( "userid", System.StringComparison.OrdinalIgnoreCase)) { key.DeleteValue("userid"); System.Console.WriteLine("Done"); } else { System.Console.WriteLine("Don't know what to clear"); } return; } string smtp = (string)key.GetValue("smtp"); if (string.IsNullOrEmpty(smtp)) { System.Console.WriteLine("smtp not set"); return; } string sport = (string)key.GetValue("port"); if (string.IsNullOrEmpty(sport)) { System.Console.WriteLine("port not set"); return; } int port; try { port = System.Convert.ToInt32(sport); } catch (System.FormatException) { System.Console.WriteLine("Port is not a sequence of digits."); return; } catch (System.OverflowException) { System.Console.WriteLine("Port cannot fit in an Int32."); return; } string to = (string)key.GetValue("to"); if (string.IsNullOrEmpty(to)) { System.Console.WriteLine("to not set"); return; } string from1 = (string)key.GetValue("from"); string userid = (string)key.GetValue("userid"); if (string.IsNullOrEmpty(to)) { System.Console.WriteLine("userid not set"); return; } System.IO.StreamReader patch_file; try { patch_file = new System.IO.StreamReader( args[0] ); } catch { System.Console.WriteLine("Cannot open file {0}", args[0]); return; } string from2 = null; string subject = null; // check the first 25 lines int line_count = 25; do { string line = patch_file.ReadLine(); if (string.IsNullOrEmpty(line)) { break; } if (line.StartsWith("Subject: ")) { subject = line.Substring(10); } if (line.StartsWith("From: ")) { from2 = line.Substring(6); } --line_count; } while (line_count > 0); if (string.IsNullOrEmpty(subject)) { System.Console.WriteLine( "'Subject: ' not found in file {0}", args[0]); return; } string workingdir = System.IO.Directory.GetCurrentDirectory(); workingdir = workingdir.Substring( workingdir.LastIndexOf('\\') + 1); subject = "[" + workingdir + ": " + subject; System.Net.Mail.SmtpClient smtpClient; try { smtpClient = new System.Net.Mail.SmtpClient(smtp, port); } catch { System.Console.WriteLine( "Cannot connect to {0} port {1}", smtp, port ); return; } System.Console.WriteLine("Please enter password for user '{0}'", userid); System.Security.SecureString pwd = getPassword(); System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential(userid, pwd); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; string from; if (!string.IsNullOrEmpty(from1)) { from = from1; } else if (string.IsNullOrEmpty(from2)) { from = from2; } else { System.Console.WriteLine( "'From: ' not found in file {0}", args[0]); System.Console.WriteLine("and from no set"); return; } patch_file.Close(); System.Net.Mail.Attachment patch = new System.Net.Mail.Attachment(args[0]); patch.ContentType.MediaType = System.Net.Mime.MediaTypeNames.Text.Plain; patch.ContentType.CharSet = "us-ascii"; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage( from, to, subject, "See attachment"); message.Attachments.Add( patch ); System.Console.WriteLine( "Sending mail\n" + " via smtp server '{0}'\n" + " port '{1}'\n" + " to '{2}'\n" + " from '{3}'\n" + " with user id '{4}'\n" + " with subject '{5}'", smtp, port, to, from, userid, subject); smtpClient.Send(message); System.Console.WriteLine( "Done" ); }
protected void Ok_Click(object sender, EventArgs e) { string templatefile; Exception ex = null; long eventid = 0; if (mode == Mode.Error && Session[Constants.SessionException] != null) { ex = (Exception)Session[Constants.SessionException]; eventid = (long)Session[Constants.SessionExceptionEventID]; templatefile = "~/Templates/ErrorFeedbackEmail.xml"; } else if (mode == Mode.JobError) { templatefile = "~/Templates/ErrorFeedbackEmail.xml"; } else { templatefile = "~/Templates/FeedbackEmail.xml"; } var template = File.ReadAllText(MapPath(templatefile)); string subject; string body; EmailTemplateUtility.LoadEmailTemplate(template, out subject, out body); EmailTemplateUtility.ReplaceEmailToken(ref subject, "[$ShortTitle]", Federation.ShortTitle); EmailTemplateUtility.ReplaceEmailToken(ref subject, "[$Subject]", Subject.Text); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$ShortTitle]", Federation.ShortTitle); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$Name]", Name.Text); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$Email]", Email.Text); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$Subject]", Subject.Text); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$Comments]", Comments.Text); if (mode == Mode.Error && Session[Constants.SessionException] != null) { EmailTemplateUtility.ReplaceEmailToken(ref body, "[$ErrorMessage]", ex.Message); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$JobGUID]", "-"); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$EventID]", eventid.ToString()); } else if (mode == Mode.JobError) { var job = new JobInstance(RegistryContext); job.Guid = jobGuid; job.Load(); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$ErrorMessage]", job.ExceptionMessage); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$JobGUID]", job.Guid.ToString()); EmailTemplateUtility.ReplaceEmailToken(ref body, "[$EventID]", "-"); } var msg = EmailTemplateUtility.CreateMessage( Federation.Email, Federation.ShortTitle, Federation.Email, Federation.ShortTitle, subject, body); // Append stack trace if (mode == Mode.Error && Session[Constants.SessionException] != null) { System.Net.Mail.Attachment att; using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(new HttpUnhandledException(ex.Message, ex).GetHtmlErrorMessage()))) { att = new System.Net.Mail.Attachment(mem, "error.html"); msg.Attachments.Add(att); EmailTemplateUtility.SendMessage(msg); } } else { EmailTemplateUtility.SendMessage(msg); } FeedbackForm.Visible = false; SuccessForm.Visible = true; }
public async Task<IActionResult> ExportToCsvAndMail() { var user = await _userManager.FindByIdAsync(User.GetUserId()); var admins = await _userManager.GetUsersInRoleAsync(AppRole.AdminsRole); var exportResult = await _customersManager.GetCustomersCSV(); if (exportResult.Succeeded) { try { var memStream = new MemoryStream(Encoding.UTF8.GetBytes(exportResult.Item.ToString())); memStream.Position = 0; var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); var reportAttachment = new System.Net.Mail.Attachment(memStream, contentType); reportAttachment.ContentDisposition.FileName = "clients.csv"; await NotificationManager.SendAsync(user.Email, admins.Select(u => u.Email).Where(e => !string.IsNullOrEmpty(e)).ToArray(), "Customers CSV", "Customers CSV", reportAttachment); return new ObjectResult(new { OK = true }); } catch (Exception ex) { NotificationManager.SendErrorMessage(ex); return HttpBadRequest(ex); } } return HttpBadRequest(); }
private static void HandleAttachments(SafeMailItemClass mailItem, UniversalRequestObject uro) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); Attachments mailAttachments = mailItem.Attachments; using (new ComObjectGovernor(mailAttachments)) { string filenames = ""; for (int i = 1; i <= mailAttachments.Count; i++) { Attachment attachmentToCopy = mailAttachments.Item(i); using (new ComObjectGovernor(attachmentToCopy)) { sb.AppendFormat("{0} ", attachmentToCopy.DisplayName); object objAttach = attachmentToCopy.AsArray; byte[] bytes = objAttach as byte[]; if (bytes != null) { System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes); bytes = null; using (System.Net.Mail.Attachment tempAttach = new System.Net.Mail.Attachment(memStream, attachmentToCopy.FileName)) { filenames += tempAttach.Name; RequestAttachment ra = new RequestAttachment { Name = tempAttach.Name, ContentType = tempAttach.ContentType.ToString(), Data = new OptimizedBinaryData(tempAttach.ContentStream) }; uro.Attachments.Add(ra); } } } } } uro.Properties.Add(MailMessagePropertyKeys.Attachments, sb.ToString()); }
public string EmailSheet(int eventID, bool results) { try { ttConnection = new SqlConnection(connection); ttConnection.Open(); } catch (Exception ex) { Trace.WriteLine(ex.Message); return ex.Message; } int emailsSent = 0; string invalid = ""; string query = string.Format("SELECT riders.name,riders.email FROM entries JOIN riders ON entries.RiderId = riders.id WHERE entries.EventId='{0}' AND riders.email is not null and riders.email!=''", eventID); try { using (SqlDataAdapter entryAdapter = new SqlDataAdapter(query, ttConnection)) { dataEntries = new DataTable(); entryAdapter.Fill(dataEntries); int length = dataEntries.Rows.Count; //riders = new List<Rider>(); System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("*****@*****.**"); System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress("*****@*****.**"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from,to); System.Net.Mail.MailAddress emailAddr; System.Net.Mail.MailAddressCollection bcc = new System.Net.Mail.MailAddressCollection(); for (int row = 0; row < length; row++) { DataRow dr = dataEntries.Rows[row]; string name = (string)dr["name"]; string email = (string)dr["email"]; try { emailAddr = new System.Net.Mail.MailAddress(email); // Valid address message.Bcc.Add(emailAddr); } catch { invalid += email; invalid += "\n\r"; } } try { emailAddr = new System.Net.Mail.MailAddress("*****@*****.**"); // Valid address message.Bcc.Add(emailAddr); } catch { invalid += "ChrisF\n\r"; } message.Subject = "Time Trial"; //message.Body = string.Format("Apologies for sending out last year's results again, please ignore!"); message.Body = string.Format("Dear rider\n\nThank you for entering the TCC event this year"); if (results) { message.Body += "\nPlease find attached results (2 documents). "; } else { message.Body += "\nPlease find attached the start details. Note that event start time has been moved to 8:00am."; message.Body += "\nPlease could you reply to this email to acknowledge receipt."; } message.Body += "\n\nRegards\nTruro Cycling Club"; try { System.Net.Mail.Attachment attach1, attach2; if (results) { attach1 = new System.Net.Mail.Attachment(@"C:\Users\Chris\Documents\tcc\TCC Open 25 July 2014.pdf"); attach2 = new System.Net.Mail.Attachment(@"C:\Users\Chris\Documents\tcc\TCC Open 25 July 2014 results.pdf"); } else { attach1 = new System.Net.Mail.Attachment(@"C:\Users\Chris\Documents\tcc\instructions2014.pdf"); attach2 = new System.Net.Mail.Attachment(@"C:\Users\Chris\Documents\tcc\list2014.pdf"); } message.Attachments.Add(attach1); message.Attachments.Add(attach2); } catch (Exception ex) { Trace.WriteLine(ex.Message); return "Could not find document(s) to attach to emails"; } try { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpserver); client.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword); client.Send(message); ++emailsSent; } catch (Exception ex) { return "There is an error with the email service: " + ex.Message; } } } catch (Exception ex) { Trace.WriteLine(ex.Message); Trace.WriteLine(emailsSent + "emails sent"); return ex.Message; } ttConnection.Close(); if (invalid.Length > 0) return ("Emails sent but these appear invalid: " + invalid); else return ("All emails sent OK"); }
public void EmailFile(string FileName) { string UserId; if (GlobalVariables.LoggedInUser != null) { UserId = GlobalVariables.LoggedInUser.id.ToString(); } else { UserId = "0"; } string timeStamp = DateTime.Now.ToString("yyyyMMddHHmm"); string directory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\XmlData\\" + UserId; //string file = directory + "\\" + FileName + timeStamp + ".xml"; System.Net.Mail.MailMessage message = null; System.Net.Mail.SmtpClient client = null; System.Net.Mail.Attachment data = null; try { // Create a message and set up the recipients. message = new System.Net.Mail.MailMessage( "*****@*****.**", "*****@*****.**", "User Test Data: " + UserId, "See the attached datafile for user " + UserId); } catch (Exception ex) { MessageBox.Show("Exception caught in CreateMessage: {0}", ex.ToString()); } try { // Create the file attachment for this e-mail message. data = new System.Net.Mail.Attachment(FileName, System.Net.Mime.MediaTypeNames.Application.Octet); // Add time stamp information for the file. System.Net.Mime.ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(FileName); disposition.ModificationDate = System.IO.File.GetLastWriteTime(FileName); disposition.ReadDate = System.IO.File.GetLastAccessTime(FileName); // Add the file attachment to this e-mail message. message.Attachments.Add(data); //Send the message. client = new System.Net.Mail.SmtpClient("smtp.grucox.com", 25) { Credentials = new System.Net.NetworkCredential("*****@*****.**", "Ant840203"), EnableSsl = false }; } catch (Exception ex) { MessageBox.Show("Exception caught in CreateAttachment: {0}", ex.ToString()); } try { client.Send(message); } catch (Exception ex) { MessageBox.Show("Exception caught in SendMessageWithAttachment(): {0} - Check internet connection.", ex.Message.ToString()); } data.Dispose(); }
private System.Net.Mail.Attachment CreateAttachment( ) { string path = this.attachmentPath + "\\" + attachmentFileName; System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment( path ); return attachment; }
/// <summary> /// 发送 /// </summary> /// <returns></returns> public bool Send() { System.Net.Mail.MailMessage myEmail = new System.Net.Mail.MailMessage(); Encoding eEncod = Encoding.GetEncoding("utf-8"); myEmail.From = new System.Net.Mail.MailAddress(this.From, this.FromName, eEncod); myEmail.To.Add(this._recipient); myEmail.Subject = this.Subject; myEmail.IsBodyHtml = this.Html; myEmail.Body = this.Body; myEmail.Priority = System.Net.Mail.MailPriority.Normal; myEmail.BodyEncoding = eEncod; //myEmail.BodyFormat = this.Html?MailFormat.Html:MailFormat.Text; //邮件形式,.Text、.Html //附件 if (this._attachemnt != null) { foreach (string attach in this._attachemnt) { System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(attach); myEmail.Attachments.Add(att); } } //优先级 switch(this._priority) { case "High": myEmail.Priority = System.Net.Mail.MailPriority.High; break; case "Low": myEmail.Priority = System.Net.Mail.MailPriority.Low; break; default: myEmail.Priority = System.Net.Mail.MailPriority.Normal; break; } System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = this.MailDomain; smtp.Port = this.MailDomainPort; smtp.Credentials = new System.Net.NetworkCredential(this.MailServerUserName, this.MailServerPassWord); //smtp.UseDefaultCredentials = true; //smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; //当不是25端口(gmail:587) if (this.MailDomainPort != 25) { smtp.EnableSsl = true; } //System.Web.Mail.SmtpMail.SmtpServer = this.MailDomain; try { smtp.Send(myEmail); } catch (System.Net.Mail.SmtpException e) { string result = e.Message; return false; } return true; }
public void SendNotification(string message, string subject, string to, string from, string login, int port, string smtpHost, string password, string attachment) { try { System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); mail.To.Add(to); mail.From = new System.Net.Mail.MailAddress(from); mail.Subject = subject; string Body = message; mail.Body = Body; if (attachment != null) { System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(attachment); mail.Attachments.Add(at); } mail.IsBodyHtml = true; using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpHost, port)) { //smtp.Host = smtpHost; //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential (from, password); //Or your Smtp Email ID and Password smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.EnableSsl = true; smtp.Send(mail); //Label1.Text = "Mail Send..."; } } catch (Exception ex) { //Label1.Text = ex.Message; } }
//private void AjustarCodigosDeReferenciaEnFooter() //{ // referenciasGridView.DataBind(); // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataValueField = "Codigo"; // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataTextField = "Descr"; // if (Funciones.SessionTimeOut(Session)) // { // Response.Redirect("~/SessionTimeout.aspx"); // } // else // { // if (((Entidades.Sesion)Session["Sesion"]).Usuario != null) // { // //if (!Punto_VentaTextBox.Text.Equals(string.Empty)) // if (!PuntoVtaDropDownList.SelectedValue.Equals(string.Empty)) // { // int auxPV; // try // { // auxPV = Convert.ToInt32(PuntoVtaDropDownList.SelectedValue); // string idtipo = ((Entidades.Sesion)Session["Sesion"]).UN.PuntosVta.Find(delegate(Entidades.PuntoVta pv) // { // return pv.Nro == auxPV; // }).IdTipoPuntoVta; // switch (idtipo) // { // case "Comun": // case "RG2904": // case "BonoFiscal": // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista(); // ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false; // ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true; // break; // case "Exportacion": // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.Exportaciones.Exportacion.Lista(); // ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = true; // ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = false; // break; // default: // throw new Exception("Tipo de punto de venta no contemplado en la lógica de la aplicación (" + idtipo + ")"); // } // } // catch // { // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista(); // ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false; // ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true; // } // } // else // { // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista(); // ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false; // ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true; // } // } // else // { // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataSource = FeaEntidades.CodigosReferencia.CodigoReferencia.Lista(); // ((AjaxControlToolkit.MaskedEditExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoMaskedEditExtender")).Enabled = false; // ((AjaxControlToolkit.FilteredTextBoxExtender)referenciasGridView.FooterRow.FindControl("txtdato_de_referenciaFooterExpoFilteredTextBoxExtender")).Enabled = true; // } // ((DropDownList)referenciasGridView.FooterRow.FindControl("ddlcodigo_de_referencia")).DataBind(); // } //} protected void AccionObtenerXMLButton_Click(object sender, EventArgs e) { if (Funciones.SessionTimeOut(Session)) { Response.Redirect("~/SessionTimeout.aspx"); } else { ActualizarEstadoPanel.Visible = false; DescargarPDFPanel.Visible = false; //ActualizarEstadoButton.DataBind(); //DescargarPDFButton.DataBind(); if (((Entidades.Sesion)Session["Sesion"]).Usuario.Id == null) { ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Su sesión ha caducado por inactividad. Por favor vuelva a loguearse."), false); } else { try { if (ValidarCamposObligatorios("ObtenerXML")) { //Generar Lote FeaEntidades.InterFacturas.lote_comprobantes lote = GenerarLote(false); //Grabar en base de datos lote.cabecera_lote.DestinoComprobante = "ITF"; lote.comprobante[0].cabecera.informacion_comprobante.Observacion = ""; //Registrar comprobante si no es el usuario de DEMO. Entidades.Sesion sesion = (Entidades.Sesion)Session["Sesion"]; if (sesion.UsuarioDemo != true) { Entidades.Comprobante cAux = new Entidades.Comprobante(); cAux.Cuit = lote.cabecera_lote.cuit_vendedor.ToString(); cAux.TipoComprobante.Id = lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante; cAux.NroPuntoVta = lote.comprobante[0].cabecera.informacion_comprobante.punto_de_venta; cAux.Nro = lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante; RN.Comprobante.Leer(cAux, sesion); if (cAux.Estado == null || cAux.Estado != "Vigente") { RN.Comprobante.Registrar(lote, null, IdNaturalezaComprobanteTextBox.Text, "ITF", "PteEnvio", PeriodicidadEmisionDropDownList.SelectedValue, DateTime.ParseExact(FechaProximaEmisionDatePickerWebUserControl.Text, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), Convert.ToInt32(CantidadComprobantesAEmitirTextBox.Text), Convert.ToInt32(CantidadComprobantesEmitidosTextBox.Text), Convert.ToInt32(CantidadDiasFechaVtoTextBox.Text), string.Empty, false, string.Empty, string.Empty, string.Empty, ((Entidades.Sesion)Session["Sesion"])); } } AjustarLoteParaITF(lote); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(lote.GetType()); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(lote.cabecera_lote.cuit_vendedor); sb.Append("-"); sb.Append(lote.cabecera_lote.punto_de_venta.ToString("0000")); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante.ToString("00")); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante.ToString("00000000")); sb.Append(".xml"); System.IO.MemoryStream m = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(m); sw.Flush(); System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1")); x.Serialize(writerdememoria, lote); m.Seek(0, System.IO.SeekOrigin.Begin); string smtpXAmb = System.Configuration.ConfigurationManager.AppSettings["Ambiente"].ToString(); System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); try { RegistrarActividad(lote, sb, smtpClient, smtpXAmb, m); } catch { } if (((Button)sender).ID == "DescargarXMLButton") { //Descarga directa del XML System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + sb.ToString()), System.IO.FileMode.Create); m.WriteTo(fs); fs.Close(); Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + sb.ToString(), false); } else { //Envio por mail del XML System.Net.Mail.MailMessage mail; if (((Entidades.Sesion)Session["Sesion"]).Usuario.Id != null) { mail = new System.Net.Mail.MailMessage("*****@*****.**", ((Entidades.Sesion)Session["Sesion"]).Usuario.Email, "Ced-eFact-Envío automático archivo XML:" + sb.ToString() , string.Empty); } else { mail = new System.Net.Mail.MailMessage("*****@*****.**", Email_VendedorTextBox.Text, "Ced-eFact-Envío automático archivo XML:" + sb.ToString() , string.Empty); } System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(); contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet; contentType.Name = sb.ToString(); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m, contentType); mail.Attachments.Add(attachment); mail.BodyEncoding = System.Text.Encoding.UTF8; mail.Body = Mails.Body.AgregarBody(); smtpClient.Host = "localhost"; if (smtpXAmb.Equals("DESA")) { string MailServidorSmtp = System.Configuration.ConfigurationManager.AppSettings["MailServidorSmtp"]; if (MailServidorSmtp != "") { string MailCredencialesUsr = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesUsr"]; string MailCredencialesPsw = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesPsw"]; smtpClient.Host = MailServidorSmtp; if (MailCredencialesUsr != "") { smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw); } smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw); } } smtpClient.Send(mail); } m.Close(); if (!smtpXAmb.Equals("DESA")) { ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');window.open('https://srv1.interfacturas.com.ar/cfeWeb/faces/login/identificacion.jsp/', '_blank');</script>", false); } else { ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Archivo enviado satisfactoriamente"), false); } } } catch (Exception ex) { ScriptManager.RegisterClientScriptBlock(this, GetType(), "Message", Funciones.TextoScript("Problemas al generar el archivo. " + ex.Message), false); } } } }
public static string Send_Email_With_Attachment(string SendTo, string SendFrom, string Subject, string Body, string AttachmentPath) { try { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); string from = SendFrom; string to = SendTo; string subject = Subject; string body = Body; bool result = regex.IsMatch(to); if (result == false) { return "Địa chỉ email không hợp lệ."; } else { try { System.Net.Mail.MailMessage em = new System.Net.Mail.MailMessage(from, to, subject, body); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(AttachmentPath); em.Attachments.Add(attach); em.Bcc.Add(from); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com";//Ví dụ xử dụng SMTP của gmail smtp.Send(em); return ""; } catch (Exception ex) { return ex.Message; } } } catch (Exception ex) { return ex.Message; } }
public static string Send_Email_With_BCC_Attachment(string SendTo, string SendBCC, string SendFrom, string Subject, string Body, string AttachmentPath) { try { System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); string from = SendFrom; string to = SendTo; //Danh sách email được ngăn cách nhau bởi dấu ";" string subject = Subject; string body = Body; string bcc = SendBCC; bool result = true; String[] ALL_EMAILS = to.Split(';'); foreach (string emailaddress in ALL_EMAILS) { result = regex.IsMatch(emailaddress); if (result == false) { return "Địa chỉ email không hợp lệ."; } } if (result == true) { try { System.Net.Mail.MailMessage em = new System.Net.Mail.MailMessage(from, to, subject, body); System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(AttachmentPath); em.Attachments.Add(attach); em.Bcc.Add(bcc); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com";//Ví dụ xử dụng SMTP của gmail smtp.Send(em); return ""; } catch (Exception ex) { return ex.Message; } } else { return ""; } } catch (Exception ex) { return ex.Message; } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="filename"></param> public static void AddAttachment(Request request, string filename) { if (!File.Exists(filename)) { filename = Path.Combine(DefaultTestDocumentPath, filename); } string name; System.Net.Mime.ContentType contentType; using (System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(filename)) { name = attachment.Name; contentType = attachment.ContentType; } Attachment requestAttachment = new Attachment(new FCS.Lite.Interface.File(filename, name), contentType.ToString(), Guid.NewGuid().ToString(), null, false) { Name = name, ContentType = contentType.ToString() }; if (request.Attachments == null) request.Attachments = new Attachment[0]; List<Attachment> attchmnts = new List<Attachment>(request.Attachments); requestAttachment.Index = attchmnts.Count.ToString(); attchmnts.Add(requestAttachment); request.Attachments = attchmnts.ToArray(); }
static void Main(string[] args) { try { if (args.Length < 5 || args.Length > 8) { Console.WriteLine(@"Usage: mailer <to> <from> <subject> <message> <smtpserver> [user] [pass] [attachfile]"); Console.WriteLine(@"Example: mailer [email protected] [email protected] ""Hello!"" ""bla bla bla"" mail.domain.com"); return; } string to = args[0]; string from = args[1]; string subject = args[2]; string body = args[3].Replace(@"\n", "\n"); string smtpServer = args[4]; string username = null; string password = null; string filename = null; if (args.Length == 6) { filename = args[5]; } if (args.Length == 7) { username = args[5]; password = args[6]; } if (args.Length == 8) { username = args[5]; password = args[6]; filename = args[7]; } Console.WriteLine("Using: to: '" + to + "' from: '" + from + "' subject: '" + subject + "' body: '" + body + "' smtpserver: '" + smtpServer + "' filename: '" + filename + "'"); System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtpServer); if (username != null && password != null) { smtpClient.Credentials = new System.Net.NetworkCredential(username, password); } System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body); if (filename != null) { System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(filename); message.Attachments.Add(att); } smtpClient.Send(message); // Sleep a little while, required for sending email to some smtp servers. System.Threading.Thread.Sleep(5000); Console.WriteLine("Done!"); } catch (System.Exception ex) { Console.WriteLine(ex.ToString()); } }
protected void GenerarButton_Click(object sender, EventArgs e) { FeaEntidades.InterFacturas.lote_comprobantes lote = new FeaEntidades.InterFacturas.lote_comprobantes(); FeaEntidades.InterFacturas.cabecera_lote cab=new FeaEntidades.InterFacturas.cabecera_lote(); cab.cantidad_reg = 1; cab.cuit_canal = Convert.ToInt64(Cuit_CanalTextBox.Text); cab.cuit_vendedor = Convert.ToInt64(Cuit_VendedorTextBox.Text); cab.id_lote = Convert.ToInt64(Id_LoteTextbox.Text); cab.presta_servSpecified = true; cab.presta_serv = Convert.ToInt32(Presta_ServCheckBox.Checked); cab.punto_de_venta = Convert.ToInt32(Punto_VentaTextBox.Text); lote.cabecera_lote = cab; FeaEntidades.InterFacturas.cabecera compcab = new FeaEntidades.InterFacturas.cabecera(); FeaEntidades.InterFacturas.informacion_comprador infcompra = new FeaEntidades.InterFacturas.informacion_comprador(); infcompra.GLN = Convert.ToInt64(GLN_CompradorTextBox.Text); infcompra.codigo_interno = Codigo_Interno_CompradorTextBox.Text; infcompra.codigo_doc_identificatorio = Convert.ToInt32(Codigo_Doc_Identificatorio_CompradorDropDownList.SelectedValue); infcompra.nro_doc_identificatorio = Convert.ToInt64(Nro_Doc_Identificatorio_CompradorTextBox.Text); infcompra.denominacion = Denominacion_CompradorTextBox.Text; infcompra.condicion_IVASpecified = true; infcompra.condicion_IVA = Convert.ToInt32(Condicion_IVA_CompradorDropDownList.SelectedValue); //infcompra.condicion_ingresos_brutosSpecified = true; //infcompra.condicion_ingresos_brutos = Convert.ToInt32(Condicion_Ingresos_Brutos_CompradorDropDownList.SelectedValue); //infcompra.nro_ingresos_brutos infcompra.inicio_de_actividades = InicioDeActividadesCompradorDatePickerWebUserControl.CalendarDateString; infcompra.contacto = Contacto_CompradorTextBox.Text; infcompra.domicilio_calle = Domicilio_Calle_CompradorTextBox.Text; infcompra.domicilio_numero = Domicilio_Numero_CompradorTextBox.Text; infcompra.domicilio_piso = Domicilio_Piso_CompradorTextBox.Text; infcompra.domicilio_depto = Domicilio_Depto_CompradorTextBox.Text; infcompra.domicilio_sector = Domicilio_Sector_CompradorTextBox.Text; infcompra.domicilio_torre = Domicilio_Torre_CompradorTextBox.Text; infcompra.domicilio_manzana = Domicilio_Manzana_CompradorTextBox.Text; infcompra.localidad = Localidad_CompradorTextBox.Text; infcompra.provincia = Provincia_CompradorTextBox.Text; infcompra.cp = Cp_CompradorTextBox.Text; infcompra.email = Email_CompradorTextBox.Text; infcompra.telefono = Telefono_CompradorTextBox.Text; compcab.informacion_comprador = infcompra; FeaEntidades.InterFacturas.informacion_comprobante infcomprob = new FeaEntidades.InterFacturas.informacion_comprobante(); infcomprob.tipo_de_comprobante = Convert.ToInt32(Tipo_De_ComprobanteDropDownList.SelectedValue); infcomprob.numero_comprobante = Convert.ToInt64(Numero_ComprobanteTextBox.Text); infcomprob.punto_de_venta = Convert.ToInt32(Punto_VentaTextBox.Text); infcomprob.fecha_emision = FechaEmisionDatePickerWebUserControl.CalendarDateString; infcomprob.fecha_vencimiento = FechaVencimientoDatePickerWebUserControl.CalendarDateString; infcomprob.fecha_serv_desde = FechaServDesdeDatePickerWebUserControl.CalendarDateString; infcomprob.fecha_serv_hasta = FechaServHastaDatePickerWebUserControl.CalendarDateString; //infcomprob.condicion_de_pago = Convert.ToInt32(Condicion_De_PagoTextBox.Text); //infcomprob.iva_computable = Iva_ComputableDropDownList.SelectedValue; //infcomprob.codigo_operacion = Codigo_OperacionDropDownList.SelectedValue; infcomprob.cae = CAETextBox.Text; infcomprob.fecha_obtencion_cae = FechaCAEObtencionDatePickerWebUserControl.CalendarDateString; infcomprob.fecha_vencimiento_cae = FechaCAEVencimientoDatePickerWebUserControl.CalendarDateString; compcab.informacion_comprobante = infcomprob; FeaEntidades.InterFacturas.informacion_vendedor infovend = new FeaEntidades.InterFacturas.informacion_vendedor(); infovend.GLN = Convert.ToInt64(GLN_VendedorTextBox.Text); infovend.codigo_interno = Codigo_Interno_VendedorTextBox.Text; infovend.razon_social = Razon_Social_VendedorTextBox.Text; infovend.cuit = Convert.ToInt64(Cuit_VendedorTextBox.Text); infovend.condicion_IVASpecified = true; infovend.condicion_IVA = Convert.ToInt32(Condicion_IVA_VendedorDropDownList.SelectedValue); //infovend.condicion_ingresos_brutosSpecified = true; //infovend.condicion_ingresos_brutos = Convert.ToInt32(Condicion_Ingresos_Brutos_VendedorDropDownList.SelectedValue); //infovend.nro_ingresos_brutos = Nro_Ingresos_Brutos_VendedorTextBox.Text; infovend.inicio_de_actividades = InicioDeActividadesCompradorDatePickerWebUserControl.CalendarDateString; infovend.contacto = Contacto_VendedorTextBox.Text; infovend.domicilio_calle = Domicilio_Calle_VendedorTextBox.Text; infovend.domicilio_numero = Domicilio_Numero_VendedorTextBox.Text; infovend.domicilio_piso = Domicilio_Piso_VendedorTextBox.Text; infovend.domicilio_depto = Domicilio_Depto_VendedorTextBox.Text; infovend.domicilio_sector = Domicilio_Sector_VendedorTextBox.Text; infovend.domicilio_torre = Domicilio_Torre_VendedorTextBox.Text; infovend.domicilio_manzana = Domicilio_Manzana_VendedorTextBox.Text; infovend.localidad = Localidad_VendedorTextBox.Text; infovend.provincia = Provincia_VendedorTextBox.Text; infovend.cp = Cp_VendedorTextBox.Text; infovend.email = Email_VendedorTextBox.Text; infovend.telefono = Telefono_VendedorTextBox.Text; compcab.informacion_vendedor = infovend; FeaEntidades.InterFacturas.comprobante comp = new FeaEntidades.InterFacturas.comprobante(); comp.cabecera = compcab; FeaEntidades.InterFacturas.detalle det = new FeaEntidades.InterFacturas.detalle(); System.Collections.Generic.List<FeaEntidades.InterFacturas.linea> listadelineas = (System.Collections.Generic.List<FeaEntidades.InterFacturas.linea>)ViewState["lineas"]; for (int i = 0; i < listadelineas.Count;i++ ) { det.linea[i] = new FeaEntidades.InterFacturas.linea(); det.linea[i].numeroLinea = i+1; det.linea[i].descripcion = listadelineas[i].descripcion; det.linea[i].importe_total_articulo = listadelineas[i].importe_total_articulo; } det.comentarios = ComentariosTextBox.Text; comp.detalle = det; FeaEntidades.InterFacturas.resumen r = new FeaEntidades.InterFacturas.resumen(); r.tipo_de_cambio = 1; r.codigo_moneda = "PES"; r.importe_total_neto_gravado = Convert.ToDouble(Importe_Total_Neto_Gravado_ResumenTextBox.Text); r.importe_total_concepto_no_gravado = Convert.ToDouble(Importe_Total_Concepto_No_Gravado_ResumenTextBox.Text); r.importe_operaciones_exentas = Convert.ToDouble(Importe_Operaciones_Exentas_ResumenTextBox.Text); r.impuesto_liq = Convert.ToDouble(Impuesto_Liq_ResumenTextBox.Text); r.impuesto_liq_rni = Convert.ToDouble(Impuesto_Liq_Rni_ResumenTextBox.Text); //r.importe_total_impuestos_nacionales = Convert.ToDouble(Importe_Total_Impuestos_Nacionales_ResumenTextBox.Text); //r.importe_total_ingresos_brutos = Convert.ToDouble(Importe_Total_Ingresos_Brutos_ResumenTextBox.Text); //r.importe_total_impuestos_municipales = Convert.ToDouble(Importe_Total_Impuestos_Municipales_ResumenTextBox.Text); //r.importe_total_impuestos_internos = Convert.ToDouble(Importe_Total_Impuestos_Internos_ResumenTextBox.Text); r.importe_total_factura = Convert.ToDouble(Importe_Total_Factura_ResumenTextBox.Text); r.observaciones = Observaciones_ResumenTextBox.Text; comp.resumen = r; lote.comprobante[0] = comp; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(lote.GetType()); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(lote.cabecera_lote.cuit_vendedor); sb.Append("-"); sb.Append(lote.cabecera_lote.punto_de_venta); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante); sb.Append(".xml"); System.IO.Stream fs = new System.IO.FileStream(sb.ToString(), System.IO.FileMode.Create); System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(fs, System.Text.Encoding.GetEncoding("ISO-8859-1")); x.Serialize(writer, lote); fs.Close(); System.IO.MemoryStream m = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(m); sw.Flush(); System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1")); x.Serialize(writerdememoria, lote); System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("*****@*****.**", Email_VendedorTextBox.Text, "Nuevo comprobante", string.Empty); m.Seek(0, System.IO.SeekOrigin.Begin); System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(); contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet; contentType.Name = sb.ToString(); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m, contentType); mail.Attachments.Add(attachment); System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Host = "vsmtpr.bancogalicia.com.ar"; smtpClient.Send(mail); m.Close(); //Envío de mail a nosotros System.Net.Mail.MailMessage mailCedeira = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**", "XML_" + lote.comprobante[0].cabecera.informacion_vendedor.cuit.ToString()+"_"+System.DateTime.Now.ToLocalTime(), string.Empty); sb = new System.Text.StringBuilder(); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.email); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.razon_social); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.telefono); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.localidad); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.contacto); sb.AppendLine(lote.comprobante[0].cabecera.informacion_vendedor.cuit.ToString()); mailCedeira.Body = sb.ToString(); smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Host = "vsmtpr.bancogalicia.com.ar"; smtpClient.Send(mailCedeira); ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');</script>"); }
public void sendmail(string attachmentFilenames, string ListTo) { try { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); string[] recipients = ListTo.Split(';'); string[] attachments = attachmentFilenames.Split(';'); foreach (string recipient in recipients) { message.To.Add(recipient); } message.Subject = "Automation Script Execution Summary Report"; message.From = new System.Net.Mail.MailAddress("*****@*****.**"); message.Body = "Please find the summary of Automation execution report attached"; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("mail2.weatherford.com"); smtp.Port = 25; foreach (string attachmentFilename in attachments) { if (System.IO.File.Exists(attachmentFilename)) { var attachment = new System.Net.Mail.Attachment(attachmentFilename); message.Attachments.Add(attachment); } } smtp.Send(message); } catch (Exception ex) { throw new Exception("Error in Sending Mails.." + ex.Message); } }
public static int SendEmail(string FromEmail, string FromName, string ToEmail, string ToName, string CC, string Subject, string Body, Data.FileItem[] Files, bool IsHtmlEmail) { try { string SMTPServer = System.Configuration.ConfigurationManager.AppSettings["SMTPServer"]; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(SMTPServer); smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; System.Net.Mail.MailMessage mess = new System.Net.Mail.MailMessage(); mess.From = new System.Net.Mail.MailAddress(FromEmail, FromName); if (ToEmail != null && ToEmail.Length > 0) { string[] _toArr = ToEmail.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string _to in _toArr) mess.To.Add(new System.Net.Mail.MailAddress(_to.Trim(), ToName)); } mess.IsBodyHtml = IsHtmlEmail; mess.Subject = Subject; mess.Body = Body; if (CC != null && CC.Length > 0) { string[] _ccArr = CC.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string _cc in _ccArr) mess.CC.Add(_cc); } // mess.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); if (Files != null) { foreach (Data.FileItem _file in Files) { System.Net.Mail.Attachment _data = new System.Net.Mail.Attachment(new System.IO.MemoryStream(_file.Data, true), _file.Name); _data.ContentDisposition.CreationDate = _file.Updated; mess.Attachments.Add(_data); } } smtp.Send(mess); return 0; } catch (Exception ex) { throw ex; } }
protected void GenerarButton_Click(object sender, EventArgs e) { if (((Button)sender).ID == "DescargarButton" && CedWebRN.Fun.NoEstaLogueadoUnUsuarioPremium((CedWebEntidades.Sesion)Session["Sesion"])) { if (!MonedaComprobanteDropDownList.Enabled) { ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Esta funcionalidad es exclusiva del SERVICIO PREMIUM. Contáctese con Cedeira Software Factory para acceder al servicio.');</script>"); } else { ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Su sesión ha caducado por inactividad. Por favor vuelva a loguearse.')</script>"); } } else { try { FeaEntidades.InterFacturas.lote_comprobantes lote = GenerarLote(); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(lote.GetType()); System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(lote.cabecera_lote.cuit_vendedor); sb.Append("-"); sb.Append(lote.cabecera_lote.punto_de_venta.ToString("0000")); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante.ToString("00")); sb.Append("-"); sb.Append(lote.comprobante[0].cabecera.informacion_comprobante.numero_comprobante.ToString("00000000")); sb.Append(".xml"); System.IO.MemoryStream m = new System.IO.MemoryStream(); System.IO.StreamWriter sw = new System.IO.StreamWriter(m); sw.Flush(); System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1")); x.Serialize(writerdememoria, lote); m.Seek(0, System.IO.SeekOrigin.Begin); string smtpXAmb = System.Configuration.ConfigurationManager.AppSettings["Ambiente"].ToString(); System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); try { RegistrarActividad(lote, sb, smtpClient, smtpXAmb, m); } catch { } if (((Button)sender).ID == "DescargarButton") { //Descarga directa del XML System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + sb.ToString()), System.IO.FileMode.Create); m.WriteTo(fs); fs.Close(); Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + sb.ToString(), false); } else { //Envio por mail del XML System.Net.Mail.MailMessage mail; if (((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Id != null) { mail = new System.Net.Mail.MailMessage("*****@*****.**", ((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Email, "Ced-eFact-Envío automático archivo XML:" + sb.ToString() , string.Empty); } else { mail = new System.Net.Mail.MailMessage("*****@*****.**", Email_VendedorTextBox.Text, "Ced-eFact-Envío automático archivo XML:" + sb.ToString() , string.Empty); } System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(); contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet; contentType.Name = sb.ToString(); System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(m, contentType); mail.Attachments.Add(attachment); mail.BodyEncoding = System.Text.Encoding.UTF8; mail.Body = Mails.Body.AgregarBody(); smtpClient.Host = "localhost"; if (smtpXAmb.Equals("DESA")) { string MailServidorSmtp = System.Configuration.ConfigurationManager.AppSettings["MailServidorSmtp"]; if (MailServidorSmtp != "") { string MailCredencialesUsr = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesUsr"]; string MailCredencialesPsw = System.Configuration.ConfigurationManager.AppSettings["MailCredencialesPsw"]; smtpClient.Host = MailServidorSmtp; if (MailCredencialesUsr != "") { smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw); } smtpClient.Credentials = new System.Net.NetworkCredential(MailCredencialesUsr, MailCredencialesPsw); } } smtpClient.Send(mail); } m.Close(); if (!smtpXAmb.Equals("DESA")) { ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');window.open('https://srv1.interfacturas.com.ar/cfeWeb/faces/login/identificacion.jsp/', '_blank');</script>"); } else { ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Archivo enviado satisfactoriamente');</script>"); } } catch (Exception ex) { ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Problemas al generar el archivo.\\n " + ex.Message + "');</script>"); } } }