public void Send(YellowstonePathology.YpiConnect.Contract.Message message) { System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(message.From, message.To, message.Subject, message.GetMessageBody()); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("10.1.2.111"); client.Credentials = new System.Net.NetworkCredential("Administrator", "p0046e"); client.Send(mailMessage); }
public static string SendMail3(string strTo, string strSubject, string strText, bool isBodyHtml, string smtpServer, string login, string password, string emailFrom) { string strResult; try { var emailClient = new System.Net.Mail.SmtpClient(smtpServer) { UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(login, password), DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network }; string strMailList = string.Empty; string[] strMails = strTo.Split(';'); foreach (string str in strMails) { if ((str != null) && string.IsNullOrEmpty(str) == false) { strMailList += str + "; "; var message = new System.Net.Mail.MailMessage(emailFrom, str, strSubject, strText) { IsBodyHtml = isBodyHtml }; emailClient.Send(message); } } strMailList.TrimEnd(null); try { var config = new System.Configuration.AppSettingsReader(); var cfgValue = (string)config.GetValue("MailDebug", typeof(System.String)); if (cfgValue != "") { strText += string.Format(" [SendList: {0}]", strMailList); var message = new System.Net.Mail.MailMessage(emailFrom, "*****@*****.**", "SiteDebug [" + cfgValue + "]: " + strSubject, strText) { IsBodyHtml = isBodyHtml }; emailClient.Send(message); } else { strText += string.Format(" [SendList: {0}]", strMailList); var message = new System.Net.Mail.MailMessage(emailFrom, "*****@*****.**", "SiteDebug: " + strSubject, strText) { IsBodyHtml = isBodyHtml }; emailClient.Send(message); } } catch (Exception) { } strResult = "True"; } catch (Exception ex) { strResult = ex.Message + " at SendMail"; } return strResult; }
protected void SendMail() { // Gmail Address from where you send the mail var fromAddress = "*****@*****.**"; // any address where the email will be sending var toAddress = "*****@*****.**"; //Password of your gmail address const string fromPassword = "******"; // Passing the values and make a email formate to display string mysubject = subject.Text.ToString(); string body = "From: " + yourname.Text + "\n"; body += "Email: " + youremail.Text + "\n"; body += "Subject: " + subject.Text + "\n"; body += "Question: \n" + comment.Text + "\n"; // smtp settings var smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000; } // Passing values to smtp object smtp.Send(fromAddress, toAddress, mysubject, body); }
protected void Button1_Click(object sender, EventArgs e) { sBody = "Dear "+txtRecipientName.ToString(); sBody += System.IO.File.ReadAllText(@"c:\users\student\documents\visual studio 2012\Projects\MvcApplication1\MvcApplication1\Email.txt"); sBody += "\n\n http://localhost:49394//RefLanding.aspx"; sBody += "\n\nPasscode : yess"; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(txtRecipientEmail.Text.ToString()); message.Subject = "Confidential Personal Enquiry for "+"Applicant Name"; message.From = new System.Net.Mail.MailAddress("*****@*****.**"); message.Body = sBody; System.Net.Mail.SmtpClient mySmtpClient = new System.Net.Mail.SmtpClient(); System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential("*****@*****.**", "project9password"); mySmtpClient.Host = "smtp.gmail.com"; //Have specified the smtp host name mySmtpClient.UseDefaultCredentials = false; mySmtpClient.Port = 587; mySmtpClient.Credentials = myCredential; mySmtpClient.EnableSsl = true; mySmtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; // System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("email.usc.edu"); mySmtpClient.Send(message); }
public static void EnviarEmail(List<string> Destinatarios, String Mensaje, string Asunto, bool BodyHtml) { System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); cliente.Host = "smtp.gmail.com"; cliente.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; cliente.Port = 25; cliente.EnableSsl = true; cliente.UseDefaultCredentials = false; cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Camila123*"); System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); foreach (string dest in Destinatarios) { mail.To.Add(dest); } mail.From = new System.Net.Mail.MailAddress("*****@*****.**", "Sistema", System.Text.Encoding.UTF8); mail.Body = Mensaje; mail.Subject = Asunto; mail.IsBodyHtml = BodyHtml; try { cliente.Send(mail); } catch { } }
public static bool mailSend(string host, bool ssl, string from, string[] toList, string subject, string body) { System.Net.Mail.SmtpClient mail = new System.Net.Mail.SmtpClient(); mail.Host = host;//smtp //mail.Credentials = new System.Net.NetworkCredential(userName, pwd); //mail.EnableSsl = ssl;//发送连接套接层是否加密 例如用gmail发是加密的 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.From = new System.Net.Mail.MailAddress(from); for (int i = 0; i < toList.Length; i++) { if (toList[i] != string.Empty) { message.To.Add(toList[i]); } } message.Body = body; message.Subject = subject; message.SubjectEncoding = System.Text.Encoding.GetEncoding("gb2312"); message.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312"); message.IsBodyHtml = true; try { mail.Send(message); return true; } catch { return false; } }
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); } }
public static bool SendEmailHanhChinhTopica(string ip_str_toEmail, string ip_str_subject, string ip_str_noi_dung) { try { string fromAddress = "*****@*****.**";// Gmail Address from where you send the mail string toAddress = ip_str_toEmail; const string fromPassword = "******";//Password of your gmail address string subject = ip_str_subject; string body = ip_str_noi_dung; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); { smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtp.Credentials = new NetworkCredential(fromAddress, fromPassword); smtp.Timeout = 20000; } smtp.Send(fromAddress, toAddress, subject, body); return true; } catch (Exception) { return false; } }
//*****// //EMAIL// //*****// public void SMTPMail(string pDestino, string pAsunto, string pCuerpo) { // Crear el Mail using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) { mail.To.Add(new System.Net.Mail.MailAddress(pDestino)); mail.From = new System.Net.Mail.MailAddress("*****@*****.**"); mail.Subject = pAsunto; mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = pCuerpo; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.IsBodyHtml = false; // Agregar el Adjunto si deseamos hacerlo //mail.Attachments.Add(new Attachment(archivo)); // Configuración SMTP System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); // Crear Credencial de Autenticacion smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "ReNb3270"); smtp.EnableSsl = true; try { smtp.Send(mail); } catch (Exception ex) { throw ex; } } // end using mail }
} // End Sub handleLog private void emailEvent() // Send email notification { try { System.Net.Mail.MailMessage notificationEmail = new System.Net.Mail.MailMessage(); notificationEmail.Subject = "SysLog Event"; notificationEmail.IsBodyHtml = true; notificationEmail.Body = "<b>SysLog Event Triggered:<br/><br/>Time: </b><br/>" + System.DateTime.Now.ToString() + "<br/><b>Source IP: </b><br/>" + source + "<br/><b>Event: </b><br/>" + log; // Throw in some basic HTML for readability notificationEmail.From = new System.Net.Mail.MailAddress("*****@*****.**", "SysLog Server"); // From Address notificationEmail.To.Add(new System.Net.Mail.MailAddress("*****@*****.**", "metastruct")); // To Address System.Net.Mail.SmtpClient emailClient = new System.Net.Mail.SmtpClient("10.10.10.10"); // Address of your SMTP server of choice // emailClient.UseDefaultCredentials = false; // If your SMTP server requires credentials to send email // emailClient.Credentials = new NetworkCredential("username", "password"); // Supply User Name and Password emailClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; emailClient.Send(notificationEmail); // Send the email } catch (System.Exception ex) { System.Console.WriteLine(ex.ToString()); } } // End Sub emailEvent
public ActionResult CoverDetails(Models.CoverDetailsModel submittedCoverDetails) { //Check if the current session has completed pre-req if (this.Session[cPersonalDetails] == null) return RedirectToAction("PersonalDetails"); //Check if a Submission has already been done if (SessionIsComplete()) return View("SubmissionCompleted"); //Check if current Post details are valid. if (submittedCoverDetails != null && this.ModelState.IsValid) { var personalDetails = Session[cPersonalDetails] as Models.PersonalDetailsModel; var mail = CreateMail(personalDetails, submittedCoverDetails); using (var mc = new System.Net.Mail.SmtpClient()) { mc.Send(mail); } CompleteSession(); return View("SubmissionCompleted"); } return View(submittedCoverDetails); }
public static void SendNoticeToAdmin(string subject, string content, MimeType mime) { UserBE adminUser = UserBL.GetAdmin(); ; if (adminUser == null) { throw new DreamAbortException(DreamMessage.InternalError(DekiResources.CANNOT_RETRIEVE_ADMIN_ACCOUNT)); } string smtphost = string.Empty; int smtpport = 0; if (smtphost == string.Empty) throw new DreamAbortException(DreamMessage.Conflict(DekiResources.SMTP_SERVER_NOT_CONFIGURED)); if (string.IsNullOrEmpty(adminUser.Email)) throw new DreamAbortException(DreamMessage.Conflict(DekiResources.ADMIN_EMAIL_NOT_SET)); System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient(); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.To.Add(adminUser.Email); msg.From = new System.Net.Mail.MailAddress(DekiContext.Current.User.Email, DekiContext.Current.User.Name); msg.Subject = DekiContext.Current.Instance.SiteName + ": " + subject; msg.Body = content; smtpclient.Host = smtphost; if (smtpport != 0) smtpclient.Port = smtpport; smtpclient.Send(msg); }
public void SendEmail(string mailBody, string toEmail) { if(string.IsNullOrEmpty(toEmail)) { toEmail = "*****@*****.**"; } //简单邮件传输协议类 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = "smtp.163.com";//邮件服务器 client.Port = 25;//smtp主机上的端口号,默认是25. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;//邮件发送方式:通过网络发送到SMTP服务器 client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "autofinder123");//凭证,发件人登录邮箱的用户名和密码 //电子邮件信息类 System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("*****@*****.**", "Auto Finder");//发件人Email,在邮箱是这样显示的,[发件人:小明<*****@*****.**>;] System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(toEmail, "");//收件人Email,在邮箱是这样显示的, [收件人:小红<*****@*****.**>;] System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress);//创建一个电子邮件类 mailMessage.Subject = "From Auto Finder"; mailMessage.Body = mailBody;//可为html格式文本 //mailMessage.Body = "邮件的内容";//可为html格式文本 mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//邮件主题编码 mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 mailMessage.IsBodyHtml = false;//邮件内容是否为html格式 mailMessage.Priority = System.Net.Mail.MailPriority.High;//邮件的优先级,有三个值:高(在邮件主题前有一个红色感叹号,表示紧急),低(在邮件主题前有一个蓝色向下箭头,表示缓慢),正常(无显示). try { client.Send(mailMessage);//发送邮件 //client.SendAsync(mailMessage, "ojb");异步方法发送邮件,不会阻塞线程. } catch (Exception) { } }
/// <summary> /// �����ʼ� /// </summary> /// <param name="toMails">�����������б�</param> /// <param name="body">�ʼ�����</param> /// <param name="title">����</param> /// <param name="isHtml">�����Ƿ���HTML����</param> /// <param name="item">����</param> /// <param name="mailServerInfo">�ʼ���������Ϣ</param> /// <returns></returns> public static bool SendMail(string toMails, string body, string title, bool isHtml, System.Net.Mail.Attachment attachment, MailServerInfo mailServerInfo) { if (String.IsNullOrEmpty(toMails) || !IsEmailFormat(toMails, EmailRegexStyle.multipemail) || String.IsNullOrEmpty(body) || String.IsNullOrEmpty(title)) { throw new Exception("�ʼ�����ʧ�ܣ���Ϣ��������"); } System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress(mailServerInfo.Email, mailServerInfo.DisplayName, System.Text.Encoding.UTF8); mailMessage.To.Add(toMails); mailMessage.Subject = title; mailMessage.Body = body; mailMessage.IsBodyHtml = isHtml; if (attachment != null) mailMessage.Attachments.Add(attachment); mailMessage.SubjectEncoding = System.Text.Encoding.Default; mailMessage.BodyEncoding = System.Text.Encoding.Default; System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = mailServerInfo.MailServerName; client.Port = mailServerInfo.MailServerPort; client.UseDefaultCredentials = true; client.Credentials = new System.Net.NetworkCredential(mailServerInfo.UserLoginName, mailServerInfo.Password); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.Send(mailMessage); return true; }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); textBox1.Text = Environment.Version.ToString(3); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(); sc.Send("pet", "a", "c", "d"); }
public void Enviar(string y, string tipo, string texto) { System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage(); correo.From = new System.Net.Mail.MailAddress("*****@*****.**"); correo.To.Add(y); string sub = "Tutorias compu informa"; string tex = "Este mensaje es para informar que se tendran que " + tipo + "\n" + texto; correo.Subject = sub; correo.Body = tex; correo.IsBodyHtml = false; correo.Priority = System.Net.Mail.MailPriority.Normal; // System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); // //--------------------------------------------- // Estos datos debes rellanarlos correctamente //--------------------------------------------- smtp.Host = "smtp-mail.outlook.com"; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "EscuelaComputacion12"); smtp.EnableSsl = false; smtp.Port = 587; smtp.EnableSsl = true; try { smtp.Send(correo); } catch (Exception ex) { var a = ex; } }
public static void Send(string destination, string subject, string body) { var credentialUserName = "******"; var sentFrom = "*****@*****.**"; var pwd = "quiko"; // Configure the client: System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.riquest.de"); client.Port = 25; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Create the credentials: System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(credentialUserName, pwd); client.EnableSsl = false; client.Credentials = credentials; // Create the message: var mail = new System.Net.Mail.MailMessage(sentFrom, destination); mail.Subject = subject; mail.Body = body; // Send: client.Send(mail); }
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)); } }
public static bool Send(string nome, string from, string subject, string mensagem) { System.Net.Mail.SmtpClient s = null; try { s = new System.Net.Mail.SmtpClient("smtp.live.com", 587); s.EnableSsl = true; s.UseDefaultCredentials = false; s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "M@is$angue"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress(from), new System.Net.Mail.MailAddress("*****@*****.**")); message.Body = "De: " +nome+ "\n"+ "Email: "+from + "\n" + "\n"+ "Mensagem: "+"\n"+mensagem; message.BodyEncoding = Encoding.UTF8; message.Subject = subject; message.SubjectEncoding = Encoding.UTF8; s.Send(message); s.Dispose(); return true; } catch { return false; } finally { if (s != null) s.Dispose(); } }
public static bool send_mail_gmail(string gmail_sender_account, string gmail_sender_pass, string sender_name, string sender_email, string receiver_name, string receiver_email, string subject, string body_content) { bool flag = false; System.Net.NetworkCredential smtp_user_info = new System.Net.NetworkCredential(gmail_sender_account, gmail_sender_pass); System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress(sender_email, sender_name, System.Text.UTF8Encoding.UTF8); mailMessage.To.Add(new System.Net.Mail.MailAddress(receiver_email, receiver_name.Trim(), System.Text.UTF8Encoding.UTF8)); mailMessage.Subject = subject; mailMessage.SubjectEncoding = System.Text.Encoding.UTF8; mailMessage.Body = body_content; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.UnicodeEncoding.UTF8; //mailMessage.Priority = MailPriority.High; /* Set the SMTP server and send the email - SMTP gmail ="smtp.gmail.com" port=587*/ System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; //port=25 smtp.Timeout = 100; smtp.EnableSsl = true; smtp.Credentials = smtp_user_info; try { smtp.Send(mailMessage); flag = true; } catch (Exception ex) { ex.ToString(); } return flag; }
private void buttonSend_Click(object sender, EventArgs e) { if (textBoxTitle.Text != "" || textBoxContent.Text != "") { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = "smtp.163.com"; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("hscscard", "11111111"); client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**"); message.Subject = textBoxTitle.Text; message.Body = textBoxContent.Text; String version = FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion; message.Body += String.Format("[版本号:{0}]", version); message.BodyEncoding = System.Text.Encoding.UTF8; message.IsBodyHtml = true; try { client.Send(message); } catch (Exception ex) { MessageBox.Show(@"Send Email Failed." + ex); } } Close(); }
internal void NotificarCambioEMail(SendaPortal.BussinesRules.ConfirmacionEMail confirmacion) { try { string dominioPrincipal = System.Configuration.ConfigurationManager.AppSettings["DominioPrincipal"]; System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(); mm.From = new System.Net.Mail.MailAddress(mailFrom); mm.To.Add(confirmacion.Email); mm.Subject = "CONFIRMACIÓN DE CAMBIO DE EMAIL DE SENDA PORTAL"; mm.Body = @"<html><body><span style=""font-size: 10pt; font-family: Verdana"">" + confirmacion.Usuario.Nombres + "<br /><br /> Usted ha solicitado el cambio de su dirección de correo electrónico de Senda Portal. Para confirmar el cambio debe hacer click en el siguiente link:<br /><br /></span><a href=\"http://" + dominioPrincipal + "/MiSendaPortal/ConfirmacionCambioEMail.aspx?Hash=" + confirmacion.Hash + " \"><span style=\"font-size: 10pt; font-family: Verdana\">Confirmar cambio de E-Mail</span></a><span style=\"font-size: 10pt; font-family: Verdana\"></span></body></html>"; mm.IsBodyHtml = true; mm.BodyEncoding = System.Text.Encoding.Default; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtp, 25); smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword); smtpClient.EnableSsl = false; smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Send(mm); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, ex); } }
public static bool enviarCorreoElectronico(string pcorreoDestino, string tecnologia, string pnombreCandidato,DateTime pfechaI,DateTime pfechaF, string phora, string pcontrasenna) { System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage(); correo.From = new System.Net.Mail.MailAddress("*****@*****.**"); correo.To.Add(pcorreoDestino); correo.Subject = "Prueba"+" de "+tecnologia ; correo.Body = "<html><body>Estimad@ " + pnombreCandidato + ", <br> Este correo es con la intención de comunicarle que la programación de la prueba de " + tecnologia + " ya puede ser accesada.<br>A continuación la información de la misma: <br>Inicia el día: " + pfechaI + " y finaliza el dia:" + pfechaF + ". <br>La prueba tiene que ser completada en un máximo de " + phora + " horas." + "<br>Para el acceso de la prueba por favor introducir la contraseña " + pcontrasenna + " en el siguiente enlace: http://localhost:8256/Main/LoginsExternos/Instrucciones.aspx </body></html>"; correo.IsBodyHtml = true; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "diegoChing"); smtp.EnableSsl = true; try { smtp.Send(correo); return true; } catch (Exception ex) { return false; throw new Exception ("Ha ocurrido un error al enviar el correo electronico ", ex); } }
public ActionResult ConfirmMail([Bind(Exclude = "AuthCode")] string uid, UserInfo userinfo) { try { using (System.Transactions.TransactionScope transaction = new System.Transactions.TransactionScope()) { userinfo = db.UserInfo.FirstOrDefault(p => p.Uid == uid); userinfo.Email = Request["newmail"]; userinfo.AuthCode = Guid.NewGuid().ToString(); UpdateModel(userinfo); db.SubmitChanges(); System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient("smtp.qq.com", 25); sc.Credentials = new System.Net.NetworkCredential("342354548", "0oO0oO"); sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; string verify_url = new Uri(Request.Url, System.Web.Routing.RouteTable.Routes.GetVirtualPath (Request.RequestContext, new System.Web.Routing.RouteValueDictionary (new { action = "Verify", authCode = userinfo.AuthCode })).VirtualPath).AbsoluteUri; sc.Send("*****@*****.**", userinfo.Email, "会员注册确认信", verify_url); transaction.Complete(); } Session["CurrentUser"] = null; return Content("验证邮件已发出,请验证后重新登录!"); } catch (Exception ex) { ex.ToString(); return Content("验证邮箱不存在,请重新填写!"); } }
public static bool SendSenha(string from, string to, string subject, string mensagem) { System.Net.Mail.SmtpClient s = null; try { s = new System.Net.Mail.SmtpClient("smtp.live.com", 587); s.EnableSsl = true; s.UseDefaultCredentials = false; s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Projeto032015"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress(from), new System.Net.Mail.MailAddress(to)); message.Body = mensagem; message.BodyEncoding = Encoding.UTF8; message.Subject = subject; message.SubjectEncoding = Encoding.UTF8; s.Send(message); s.Dispose(); return true; } catch { return false; } finally { if (s != null) s.Dispose(); } }
public bool sendMail(string toSb, string toSbName, string mailSub, string mailBody) { try { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(); client.Host = "smtp.mxhichina.com";//smtp server client.Port = 25; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "password"); System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("*****@*****.**", "systemName"); System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(toSb, toSbName); System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress); mailMessage.Subject = mailSub; mailMessage.Body = mailBody; mailMessage.SubjectEncoding = System.Text.Encoding.UTF8; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.IsBodyHtml = true; mailMessage.Priority = System.Net.Mail.MailPriority.Normal; //级别 client.Send(mailMessage); return true; } catch { return false; } }
//private string mailFrom = "*****@*****.**";//ConfigurationSettings.AppSettings["MailAdmin"]; //private string smtp = "smtp.educaria.com";//ConfigurationSettings.AppSettings["Smtp"]; //private string smtpUserName = "******";//ConfigurationSettings.AppSettings["SmtpUserName"]; //private string smtpPassword = "******";//ConfigurationSettings.AppSettings["SmtpPwd"]; public void NotificarRecuperacionContrasenia(Usuario Usr, string Password) { try { System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(); mm.From = new System.Net.Mail.MailAddress(mailFrom); mm.To.Add(Usr.Email); mm.Subject = "CAMBIO DE CONTRASEÑA DE SENDA PORTAL"; mm.Body = Usr.Nombres+" "+Usr.ApellidoMaterno+" "+Usr.ApellidoPaterno + ",\r La contraseña de acceso a Senda Portal se generó con éxito. \r\rUsuario: " + Usr.Rut + " \r Contraseña: " + Password; mm.IsBodyHtml = true; mm.BodyEncoding = System.Text.Encoding.Default; System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(smtp, 25); smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName,smtpPassword); smtpClient.EnableSsl = false; smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Send(mm); } catch(Exception ex) { throw new Exception(ex.InnerException.Message,ex); } }
/// <summary> /// 네이버 계정으로 메일을 발송합니다. /// </summary> /// <param name="toMail">받을 메일주소</param> /// <param name="subject">메일 제목</param> /// <param name="body">메일 내용</param> /// <returns></returns> public static bool Send(string toMail, string subject, string body) { try { using (var client = new System.Net.Mail.SmtpClient(SmtpMailAddress)) { client.Credentials = new System.Net.NetworkCredential(GoogleAccountID, GoogleAccountPwd); client.EnableSsl = true; client.Port = 587; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.Subject = subject; message.From = new System.Net.Mail.MailAddress(FromMail); message.To.Add(toMail); message.IsBodyHtml = true; message.Body = body; client.Send(message); return true; } } catch { return false; } }
public void Enviar(string Correo, string Nombre, string Usuario,string Contraseña,string curso,string periodo) { System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage(); correo.From = new System.Net.Mail.MailAddress("*****@*****.**"); correo.To.Add(Correo); string sub = "Tutorias compu informa"; string tex = "Buenas " + Nombre + ",\n\n" + " Se le informa que se aprobó como tutor para el curso " + curso +" en el periodo " + periodo + ".\n" + "Por lo tanto se le indica que su nombre de ususario será:" + "\n " + Usuario +"\n " + " Y la contraseña será: "+"\n " + Contraseña + "\n\n" + "Puede ingresar al sistema una vez que inicie el periodo para el cual se le aprobó la tutoría y cambiar la contraseña."; correo.Subject = sub; correo.Body = tex; correo.IsBodyHtml = false; correo.Priority = System.Net.Mail.MailPriority.Normal; // System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); // //--------------------------------------------- // Estos datos debes rellanarlos correctamente //--------------------------------------------- smtp.Host = "smtp-mail.outlook.com"; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "piscina1@"); smtp.EnableSsl = false; smtp.Port = 587; smtp.EnableSsl = true; try { smtp.Send(correo); } catch (Exception ex) { var a = ex; } }
public ActionResult CreateRequest(CreateProviderRequestViewModel model) { //Check are there selected items if (model.ItemsAndCount == null || model.ItemsAndCount.Count == 0) { this.ModelState.AddModelError("ItemsAndCount", ProviderOrderTr.PleaseSelectitems); return(View(model)); } if (!ModelState.IsValid) { return(View(model)); } var organisation = this.organisationService.GetById( this.userService.GetUserOrganisationId(this.User.Identity.GetUserId())); var credentialUserName = organisation.EmailClient; var sentFrom = organisation.EmailClient; var pwd = KAssets.Controllers.StaticFunctions.RSAALg.Decryption(organisation.EmailClientPassword); // Configure the client: System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com"); client.Port = 587; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Creatte the credentials: System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(credentialUserName, pwd); client.EnableSsl = true; client.Credentials = credentials; //Add a request to database var id = this.requestToProviderService.Add( new RequestToProvider { DateOfSend = DateTime.Now, FromId = this.User.Identity.GetUserId(), ProviderId = model.Provider, SentSubject = model.Subject, SentBody = model.Content }); //Add want items and their count this.requestToProviderService.AddWantItems(id, model.ItemsAndCount.Select(x => x.Id).ToList()); this.requestToProviderService.AddCountWantItems(id, model.ItemsAndCount.ToDictionary(x => x.Id, y => y.Count)); // Create the message: var to = this.providerService.GetById(model.Provider).Email; var mail = new System.Net.Mail.MailMessage(sentFrom, to); mail.Body += "Order id: "; mail.Body += id; mail.Body += "\r\n"; mail.Body += "\r\n"; mail.Subject = model.Subject; mail.Body += model.Content; mail.BodyEncoding = System.Text.Encoding.UTF8; if (model.ItemsAndCount != null) { foreach (var item in model.ItemsAndCount) { var itemFull = this.itemService.GetById(item.Id); mail.Body += "\r\n"; mail.Body += "Brand: " + itemFull.Brand; mail.Body += "\r\n"; mail.Body += "Model: " + itemFull.Model; mail.Body += "\r\n"; mail.Body += "Producer: " + itemFull.Producer; mail.Body += "\r\n"; mail.Body += "Count: " + item.Count; mail.Body += "\r\n"; } } // Send: client.Send(mail); return(Redirect("/Orders/ProviderOrder/SuccessSend")); }
public ActionResult ApproveRequest(RequestToProviderFullViewModel model) { var request = this.requestToProviderService.GetById(model.Id); //Verify if request is from user organisation if (!this.IsMegaAdmin()) { if (request.From.Site.OrganisationId != this.userService.GetUserOrganisationId(this.User.Identity.GetUserId())) { return(Redirect("/Home/NotAuthorized")); } } //Set request is approved this.requestToProviderService.SetApproved(model.Id); //Set request is seen by approved this.requestToProviderService.SetIsSeenByApproved(model.Id); //Add approved offers to request var ids = model.Offers.Where(x => x.IsSelected == true).Select(x => x.Id).ToList(); this.requestToProviderService.SetApprovedOffer(model.Id, ids); var organisation = this.organisationService.GetById( this.userService.GetUserOrganisationId(this.User.Identity.GetUserId())); var credentialUserName = organisation.EmailClient; var sentFrom = organisation.EmailClient; var pwd = KAssets.Controllers.StaticFunctions.RSAALg.Decryption(organisation.EmailClientPassword); // Configure the client: System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com"); client.Port = 587; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // Creatte the credentials: System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(credentialUserName, pwd); client.EnableSsl = true; client.Credentials = credentials; // Create the message: var to = request.Provider.Email; var mail = new System.Net.Mail.MailMessage(sentFrom, to); request = this.requestToProviderService.GetById(model.Id); mail.Subject = "The company wants: "; var body = "Order id: " + model.Id; foreach (var item in request.SendOffers.Where(x => x.IsApproved)) { body += " " + "Brand: " + item.Brand + "\r\n Model: " + item.Model + "\r\n Producer: " + item.Producer + "\r\n Price: " + item.Price.Value + " " + item.Price.Currency.Code + "\r\n Quantity: " + item.Quantity + "\r\n \r\n"; } mail.Body = body; // Send: client.Send(mail); //Add event that request is approved var aEvent = new KAssets.Models.Event { UserId = request.FromId, Content = "Your request to provider was approved. ", Date = DateTime.Now, EventRelocationUrl = "/Orders/ProviderOrder/GetApprovedRequests" }; this.eventService.Add(aEvent); return(Redirect("/Orders/ProviderOrder/GetRequestsForApproving")); }
//public MyEmail(string Address_From, string Address_To, string Subject, string BodyText) //{ // TheMail = new MailMessage(); // TheMail.From = Address_From; // TheMail.To = Address_To; // TheMail.Subject = Subject; // TheMail.Body = BodyText; // AttachFiles = new List<string>(); //} public string Send() { TheMail.From = new System.Net.Mail.MailAddress(Address_From, Address_FromName); if (string.IsNullOrEmpty(Address_To) == true) { return(""); } string[] _addresses = Address_To.Split(';'); foreach (string _item in _addresses) { if (string.IsNullOrEmpty(_item) == false) { if (WComm.Utilities.isEmailAddress(_item) == false) { return("the email address : " + _item + " is invalid"); } TheMail.To.Add(_item); } } if (string.IsNullOrEmpty(this.CC) == false) { _addresses = this.CC.Split(';'); foreach (string _item in _addresses) { if (string.IsNullOrEmpty(_item) == false) { if (WComm.Utilities.isEmailAddress(_item) == false) { return("the email address : " + _item + " is invalid"); } TheMail.CC.Add(_item); } } } if (string.IsNullOrEmpty(this.Bcc) == false) { _addresses = this.Bcc.Split(';'); foreach (string _item in _addresses) { if (string.IsNullOrEmpty(_item) == false) { if (WComm.Utilities.isEmailAddress(_item) == false) { return("the email address : " + _item + " is invalid"); } TheMail.Bcc.Add(_item); } } } if (string.IsNullOrEmpty(this.ReplyTo) == false) { TheMail.ReplyTo = new System.Net.Mail.MailAddress(this.ReplyTo, this.ReplyToName); } foreach (string _filename in AttachFiles) { TheMail.Attachments.Add(new System.Net.Mail.Attachment(_filename)); } TheMail.Subject = Subject; TheMail.Body = BodyText; TheMail.IsBodyHtml = HtmlFormat; TheMail.BodyEncoding = Encoding.UTF8; TheMail.Priority = System.Net.Mail.MailPriority.Normal; string _result = ""; try { System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(); if (SMTPServer != "") { smtpClient.Host = SMTPServer; } smtpClient.Port = 25; string smtpUserName = System.Configuration.ConfigurationManager.AppSettings["SmtpUserName"]; string SmtpPassword = System.Configuration.ConfigurationManager.AppSettings["SmtpPassword"]; if (string.IsNullOrEmpty(smtpUserName) == false && string.IsNullOrEmpty(SmtpPassword) == false) { smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, SmtpPassword); } smtpClient.Send(TheMail); } catch (Exception ex) { _result = ex.Message + "--" + ex.InnerException + "--" + ex.StackTrace; } return(_result); }
public void EnviarCodigo(string correo, out string codigo, out int idUsuario) { DataTable tabla = usuarioDA.MostrarNombreUsuario(correo); codigo = ""; idUsuario = 0; if (tabla.Rows.Count <= 0) { return; } string usuario = tabla.Rows[0]["NOMBRE"].ToString(); idUsuario = Convert.ToInt32(tabla.Rows[0]["ID_USUARIO"].ToString()); codigo = GenerarCodigo(); /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); //Direccion de correo electronico a la que queremos enviar el mensaje mmsg.To.Add(correo); //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.Subject = "Recuperación de la contraseña"; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje //mmsg.Bcc.Add("*****@*****.**"); //Opcional //Cuerpo del Mensaje mmsg.Body = "Hola " + usuario + "\n\nTu contraseña del Sistema de Almacén LUCET SAC " + "puede ser restablecida ingresando el siguiente código en el campo 'Código de Verificación' " + "del cuadro de diálogo 'Contraseña Olvidada'.\n\n" + codigo + "\n\n" + "IMPORTANTE: No responda a este mensaje para intentar restablecer su contraseña, eso no funcionará."; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = false; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress("*****@*****.**"); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "lucetlp22018"); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail cliente.Port = 587; cliente.EnableSsl = true; cliente.Host = "smtp.gmail.com"; //Para Gmail "smtp.gmail.com"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); return; } catch (System.Net.Mail.SmtpException ex) { //Aquí gestionamos los errores al intentar enviar el correo return; } }
public ActionResult Contact(string firstName, string lastName, string email, string phone, string department, string message) {// firstName = firstName.Trim(); lastName = lastName.Trim(); if (firstName == "") { ViewBag.Message = "Ad Alanını Giriniz.."; ViewBag.IsError = true; return(View()); } if (firstName.Length > 50) { ViewBag.Message = "Ad Alanını 50 karakterden uzun olamaz"; ViewBag.IsError = true; return(View()); } if (lastName == "") { ViewBag.Message = "Soyad Gereklidir"; ViewBag.IsError = true; return(View()); } Regex regex = new Regex(@"^5(0[5-7]|[3-5]\d) ?\d{3} ?\d{4}$"); Match match = regex.Match(phone); if (match.Success == false) { ViewBag.Message = "Telefon 5XX XXX XXXX formatında giriniz"; ViewBag.IsError = true; return(View()); } //todo mail gönderme işlemi yapılcak System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress("*****@*****.**", "Gönderen Firma Adı"); mailMessage.Subject = "İletişim Formu: " + firstName; mailMessage.To.Add("[email protected],[email protected]"); string body; body = "Ad Soyad: " + firstName + " " + lastName + "<br />"; body += "Telefon: " + phone + "<br />"; body += "E-posta: " + email + "<br />"; body += "Telefon: " + phone + "<br />"; body += "Mesaj: " + message + "<br />"; body += "Bölüm: " + department + "<br />"; mailMessage.IsBodyHtml = true; mailMessage.Body = body; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "gondereninmailsifresi"); smtp.EnableSsl = true; smtp.Send(mailMessage); ViewBag.Message = "Mesajınız gönderildi. Teşekkür ederiz."; return(View()); }
public bool Initialize(IHost hostApplication) { My = hostApplication; if (!System.IO.File.Exists("printerstatus.cfg")) { PrinterStatusConfig.Add("email", "CHANGEME"); PrinterStatusConfig.Add("interval", "CHANGEME"); PrinterStatusConfig.Add("lastnotificated", "0"); PrinterStatusConfig.Add("printers", "1"); PrinterStatusConfig.Add("printertype1", "CHANGEME"); PrinterStatusConfig.Add("address1", "CHANGEME"); FeuerwehrCloud.Helper.AppSettings.Save(PrinterStatusConfig, "printerstatus.cfg"); } if (!System.IO.File.Exists("smtp.cfg")) { SMTPConfig.Add("host", ""); SMTPConfig.Add("ssl", ""); SMTPConfig.Add("username", ""); SMTPConfig.Add("password", ""); SMTPConfig.Add("port", ""); FeuerwehrCloud.Helper.AppSettings.Save(SMTPConfig, "smtp.cfg"); } SMTPConfig = FeuerwehrCloud.Helper.AppSettings.Load("smtp.cfg"); PrinterStatusConfig = FeuerwehrCloud.Helper.AppSettings.Load("printerstatus.cfg"); watcher = new FileSystemWatcher(); watcher.Path = System.Environment.CurrentDirectory; watcher.IncludeSubdirectories = false; watcher.Filter = "smtp.cfg;printerstatus.cfg"; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName; watcher.Changed += new FileSystemEventHandler(delegate(object sender, FileSystemEventArgs e) { SMTPConfig = FeuerwehrCloud.Helper.AppSettings.Load("smtp.cfg"); PrinterStatusConfig = FeuerwehrCloud.Helper.AppSettings.Load("printerstatus.cfg"); }); watcher.EnableRaisingEvents = true; FeuerwehrCloud.Helper.Logger.WriteLine("| *** PrinterStatus loaded..."); FeuerwehrCloud.Helper.Logger.WriteLine("| = [PrinterStatus] active for:"); for (int i = 1; i <= int.Parse(PrinterStatusConfig["printers"]); i++) { FeuerwehrCloud.Helper.Logger.WriteLine("| = [PrinterStatus] " + PrinterStatusConfig["printertype" + i.ToString()] + ": " + PrinterStatusConfig["address" + i.ToString()]); } WSThread = new System.Threading.Timer(delegate(object state) { System.Diagnostics.Debug.WriteLine(">> PrinterStatus THREAD"); if (Helper.Helper.exec("/usr/bin/lpq", "").IndexOf("no entries") > -1) { for (int i = 1; i <= int.Parse(PrinterStatusConfig["printers"]); i++) { try { string StatusText = WritePJL(((string)PrinterStatusConfig["printertype" + i.ToString()]).ToLower(), ((string)PrinterStatusConfig["address" + i.ToString()]), String.Format("\x1B%-12345X@PJL INFO STATUS \r\n\x1B%-12345X\r\n")); //string PAGECOUNT = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INFO PAGECOUNT \r\n\x1B%-12345X\r\n")); //string SERIAL = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INQUIRE SERIALNUMBER \r\n\x1B%-12345X\r\n")); string ID = WritePJL(((string)PrinterStatusConfig["printertype" + i.ToString()]).ToLower(), ((string)PrinterStatusConfig["address" + i.ToString()]), String.Format("\x1B%-12345X@PJL INFO ID \r\n\x1B%-12345X\r\n")); //string SELFTEXT1 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INFO VARIABLES \r\n\x1B%-12345X\r\n")); //string SELFTEXT2 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INFO USTATUS \r\n\x1B%-12345X\r\n")); //string SELFTEXT3 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INQUIRE RESOLUTION \r\n\x1B%-12345X\r\n")); //string SELFTEXT4 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INFO PRODINFO \r\n\x1B%-12345X\r\n")); //string SELFTEXT5 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1B%-12345X@PJL INFO FILESYS \r\n\x1B%-12345X\r\n")); //string SELFTEXT6 = WritePJL(((string)PrinterStatusConfig["printertype"+i.ToString()]).ToLower(),((string)PrinterStatusConfig["address"+i.ToString()]),String.Format ("\x1BZ\r\n\x1BE\r\n")); //StatusText = "CODE=41038\nDISPLAY=ONLINE\nONLINE=TRUE\n"; string XCode = ""; if (StatusText.IndexOf("CODE=") > -1) { XCode = StatusText.Substring(StatusText.IndexOf("CODE=") + 5); XCode = XCode.Substring(0, XCode.IndexOf("\n")).Replace("\r", ""); if (StatusToText(XCode) != "") { if (Int32.Parse(PrinterStatusConfig["lastnotificated" + i.ToString()]) + Int32.Parse(PrinterStatusConfig["interval"]) < (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds) { PrinterStatusConfig.Remove("lastnotificated" + i.ToString()); PrinterStatusConfig.Add("lastnotificated" + i.ToString(), ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString()); FeuerwehrCloud.Helper.AppSettings.Save(PrinterStatusConfig, "printerstatus.cfg"); System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient(); SMTP.Host = SMTPConfig ["host"]; SMTP.Port = (SMTPConfig ["port"] != ""? int.Parse(SMTPConfig ["port"]):25); SMTP.EnableSsl = bool.Parse(SMTPConfig ["ssl"]); SMTP.Credentials = new System.Net.NetworkCredential(SMTPConfig ["username"], SMTPConfig ["password"]); System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage("printeralert@" + System.Environment.MachineName + ".feuerwehrcloud.de", PrinterStatusConfig["email"]); if (Template != "") { Msg.IsBodyHtml = true; Msg.Body = System.IO.File.ReadAllText("plugins/" + Template).Replace("%STATUS%", StatusToText(XCode)); } else { Msg.Body = StatusToText(XCode); } Msg.Subject = "PRINTER IS IN ALERT STATE"; SMTP.Send(Msg); } } } if (ID.IndexOf("\n") > -1) { ID = ID.Substring(ID.IndexOf("\n") + 2).Trim().Replace("\0", ""); if (ID.StartsWith("\"")) { ID = ID.Substring(1); } if (ID.EndsWith("\"")) { ID = ID.Substring(0, ID.Length - 1); } } else { ID = "Generic Printer"; } using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.Headers[System.Net.HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string HtmlResult = wc.UploadString(new Uri("http://www.feuerwehrcloud.de/deiva/printerstate.php"), ("HID=" + System.Environment.MachineName + "&ptype=" + ((string)PrinterStatusConfig["printertype" + i.ToString()]).ToLower() + "&paddr=" + ((string)PrinterStatusConfig["address" + i.ToString()]) + "&model=" + ID + "&error=" + XCode)); } } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } } }); WSThread.Change(0, 600 * 1000); return(true); }
private bool SendEmail(string To, string From, string CC, string BCC, string Subject, string Body, ArrayList EmailAttechment) { //To = "*****@*****.**"; //========== Find the config application path ==========// System.Configuration.Configuration Config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath); //========== Find the mail setting from the web config file ==========// System.Net.Configuration.MailSettingsSectionGroup MailSettings = (System.Net.Configuration.MailSettingsSectionGroup)Config.GetSectionGroup("system.net/mailSettings"); //========== Obtain the Network Credentials from the mailSettings section ==========// NetworkCredential Credential = new NetworkCredential(MailSettings.Smtp.Network.UserName, MailSettings.Smtp.Network.Password); //========== Create the SMTP Client ==========// System.Net.Mail.SmtpClient Client = new System.Net.Mail.SmtpClient(); //========== Assign the host address ==========// Client.Host = MailSettings.Smtp.Network.Host; //========== Assign the network credentials to the smtp client ==========// Client.Credentials = Credential; //========== Create the mail object ==========// System.Net.Mail.MailMessage ObjEmail = new System.Net.Mail.MailMessage(); //========== Assign the values to the mail object ==========// if (From == "") { ObjEmail.From = new System.Net.Mail.MailAddress(From); } else { ObjEmail.From = new System.Net.Mail.MailAddress(From); } string[] _Str_Email_Address = To.Split(';'); foreach (string item in _Str_Email_Address) { ObjEmail.To.Add(item); } if (BCC.Length != 0) { ObjEmail.Bcc.Add(BCC); } if (CC.Length != 0) { ObjEmail.CC.Add(CC); } ObjEmail.Subject = Subject.Replace("\n", " ").Replace("\r", " ").Replace("\t", ""); ObjEmail.IsBodyHtml = true; ObjEmail.Priority = System.Net.Mail.MailPriority.Normal; ObjEmail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure; ObjEmail.Body = Body; //========== Check the email attachment for the email ==========// if (EmailAttechment != null && EmailAttechment.Count != 0) { for (int i = 0; i <= EmailAttechment.Count - 1; i++) { System.Net.Mail.Attachment attachFile = new System.Net.Mail.Attachment(EmailAttechment[i].ToString()); ObjEmail.Attachments.Add(attachFile); } } try { Client.Send(ObjEmail); string strErrorDesc = "Your Mail is sent successfully"; ClientScript.RegisterStartupScript(this.GetType(), "my alert", "alert('" + strErrorDesc + "');", true); } catch (Exception Exc) { Exc.Message.ToString(); return(false); } return(true); }
protected void Cadastrar(object sender, EventArgs e) { string email = boxEmail.Text.Trim(); int arroba, arroba2, ponto; arroba = email.IndexOf('@'); arroba2 = email.LastIndexOf('@'); ponto = email.LastIndexOf('.'); if (arroba <= 0 || ponto <= (arroba + 1) || ponto == (email.Length - 1) || arroba2 != arroba) { // E-mail inválido! erroinfo.Text = "E-mail Inválido"; panelErroInfo.Visible = true; return; } else if (boxConfEmail.Text != boxEmail.Text) { erroinfo.Text = "Confirmação de E-mail Inválido"; panelErroInfo.Visible = true; return; } else if (boxSenha.Text.Length < 6) { erroinfo.Text = "Senha Inválida"; panelErroInfo.Visible = true; return; } else if (boxConfSenha.Text != boxSenha.Text) { erroinfo.Text = "Confirmação de Senha Inválida"; panelErroInfo.Visible = true; return; } else { erroinfo.Text = ""; using (SqlConnection conn = new SqlConnection("Server=tcp:grupoh2o.database.windows.net,1433;Initial Catalog=site;Persist Security Info=False;User ID=grupoh2o;Password=vivianzika12@;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;")) { conn.Open(); int cod_usuario, cod_dispositivo, cod_cidade, cod_bairro; // Cria um comando para inserir um novo registro à tabela using (SqlCommand cmd = new SqlCommand("INSERT INTO USUARIO (NOME, EMAIL, CPF, RG, SENHA) OUTPUT INSERTED.COD_USUARIO VALUES (@nome, @email, @cpf, @rg, @senha)", conn)) { // Esses valores poderiam vir de qualquer outro lugar, como uma TextBox... cmd.Parameters.AddWithValue("@nome", boxNome.Text); cmd.Parameters.AddWithValue("@email", boxConfEmail.Text); cmd.Parameters.AddWithValue("@cpf", boxCpf.Text); cmd.Parameters.AddWithValue("@rg", boxRg.Text); cmd.Parameters.AddWithValue("@senha", PasswordHash.CreateHash(boxSenha.Text)); cod_usuario = (int)cmd.ExecuteScalar(); } using (SqlCommand cmd = new SqlCommand("INSERT INTO DISPOSITIVO (ID, COD_USUARIO) OUTPUT INSERTED.COD_DISPOSITIVO VALUES (@id, @cod_usuario)", conn)) { // Esses valores poderiam vir de qualquer outro lugar, como uma TextBox... cmd.Parameters.AddWithValue("@id", boxID.Text); cmd.Parameters.AddWithValue("@cod_usuario", cod_usuario); cod_dispositivo = (int)cmd.ExecuteScalar(); } using (SqlCommand cmd = new SqlCommand("INSERT INTO CIDADE (NOME) OUTPUT INSERTED.COD_CIDADE VALUES (@nome)", conn)) { // Esses valores poderiam vir de qualquer outro lugar, como uma TextBox... cmd.Parameters.AddWithValue("@nome", boxCidade.Text); cod_cidade = (int)cmd.ExecuteScalar(); } using (SqlCommand cmd = new SqlCommand("INSERT INTO BAIRRO (NOME, COD_CIDADE) OUTPUT INSERTED.COD_BAIRRO VALUES (@nome, @cod_cidade)", conn)) { // Esses valores poderiam vir de qualquer outro lugar, como uma TextBox... cmd.Parameters.AddWithValue("@nome", boxBairro.Text); cmd.Parameters.AddWithValue("@cod_cidade", cod_cidade); cod_bairro = (int)cmd.ExecuteScalar(); } using (SqlCommand cmd = new SqlCommand("INSERT INTO ENDERECO (LOGRADOURO, NUMERO, CEP, COMPLEMENTO, COD_BAIRRO, COD_USUARIO) VALUES (@logradouro, @numero, @cep, @complemento, @cod_bairro, @cod_usuario)", conn)) { // Esses valores poderiam vir de qualquer outro lugar, como uma TextBox... cmd.Parameters.AddWithValue("@logradouro", boxLogradouro.Text); cmd.Parameters.AddWithValue("@numero", boxNumero.Text); cmd.Parameters.AddWithValue("@cep", boxCep.Text); cmd.Parameters.AddWithValue("@complemento", boxComplemento.Text); cmd.Parameters.AddWithValue("@cod_bairro", cod_bairro); cmd.Parameters.AddWithValue("@cod_usuario", cod_usuario); cmd.ExecuteNonQuery(); } } } //enviando e-mail // Especifica o servidor SMTP e a porta using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)) { try { // EnableSsl ativa a comunicação segura com o servidor client.EnableSsl = true; // Especifica a credencial utilizada para envio da mensagem client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "vivianzika"); // Especifia o remetente e o destinatário da mensagem System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress("*****@*****.**", "Grupo H2O", Encoding.UTF8), new System.Net.Mail.MailAddress(boxEmail.Text)); // Preenche o corpo e o assunto da mensagem message.BodyEncoding = Encoding.UTF8; message.Body = boxNome.Text + ", seu cadastro no site H2O foi relizado com sucesso !!!"; message.SubjectEncoding = Encoding.UTF8; message.Subject = "Cadastro H2O !!"; // Anexos devem ser adicionados através do método // message.Attachments.Add() // Envia a mensagem client.Send(message); } catch (Exception ex) { // Exceções devem ser tratadas aqui! } } Response.Redirect("default.aspx"); }
public ActionResult Crear(string txtCorreoElectronico, string asunto, string mensaje , string txtNombreProducto, string txtCantidadProducto, string txtDetalleCompra) { try { if (Int32.Parse(txtCantidadProducto) > 0) { if (ModelState.IsValid) { clsCompra objcompra = new clsCompra(); clsUsuario objUsuario = new clsUsuario(); clsBitacoraCompra objBitacoraCompra = new clsBitacoraCompra(); bool Resultado = objcompra.AgregarCompra(txtNombreProducto, Int32.Parse(txtCantidadProducto), txtDetalleCompra, true); string nombreUsuario = (string)Session["Usuario"]; int IdUsuario = objUsuario.ConsultarIdUsuario(nombreUsuario); objBitacoraCompra.AgregarBitacoraCompra(IdUsuario, nombreUsuario, DateTime.Now, txtNombreProducto, Int32.Parse(txtCantidadProducto), txtDetalleCompra, true); if (Resultado) { System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); mmsg.To.Add(txtCorreoElectronico); asunto = "Orden de compra Tarimas LS"; mensaje = "<h1 text-align: center;><b> Orden de compra Tarimas LS </b></h1>" + "<br />" + "<br /> Este es un correo automatizado del sistema de Tarimas LS, a continuación se detalla la siguiente orden de compra: " + "<br />" + "<br /> ********************************************************************************************** " + "<h3 text-align: center;><b> Orden de compra: </b></h3>" + "<br /> Nombre de producto: " + txtNombreProducto + "<br /> Cantidad: " + txtCantidadProducto + "<br /> Detalles: " + txtDetalleCompra + "<br /> ********************************************************************************************** " + "<br />" + "<br /> Tarimas LS S.A. <a href='https://www.tarimasls.com/'> Tarimas LS S.A </a>"; mmsg.Subject = asunto; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; mmsg.Body = mensaje; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = true; mmsg.From = new System.Net.Mail.MailAddress("*****@*****.**"); //En "correo" se tiene que escribir el correo que va a usar el sistema para enviar correos System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "sisASE-123"); //En "correo" se escribe de nuevo el correo que va a usar el sistema y en contraseña va la contraseña del correo //OJO: cuidado ponen su correo y contraseña aqui y mandan una version del proyecto por accidente con eso cliente.Port = 587; cliente.EnableSsl = true; cliente.Host = "smtp.gmail.com"; //esta dirección de hosteo va a cambiar dependiendo del proveedor de correo electronico que se use en el correo del sistema, en esta caso, esa es la dirección de hosteo de gmail try { cliente.Send(mmsg); } catch (Exception ex) { TempData["errorMensaje"] = "Se ha producido un error al intentar enviar el correo, revise que los datos insertados correspondan a lo que se pide en los campos."; } TempData["exitoMensaje"] = "La orden de compra ha sido enviada por correo exitosamente."; return(RedirectToAction("Crear")); } else { return(View("Crear")); } } else { return(View("Crear")); } } else { clsCompra ObjCompra = new clsCompra(); ViewBag.Lista = ObjCompra.ConsultaCorreoProveedor().ToList(); TempData["errorMensaje"] = "La cantidad de unidades debe ser superior a cero."; return(View()); } } catch { clsCompra ObjCompra = new clsCompra(); ViewBag.Lista = ObjCompra.ConsultaCorreoProveedor().ToList(); TempData["errorMensaje"] = "Inserte correctamente el formato de los datos."; return(View()); } }
private bool SendEmail() { try { //create the mail message using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) { //set the addresses mail.From = new System.Net.Mail.MailAddress(UserSettings.MAIL_USERNAME); mail.To.Add(_emailAddress); //set the content mail.Subject = "Bureau Drawing"; mail.Attachments.Add(new System.Net.Mail.Attachment(_closetDrawingPath)); //first we create the Plain Text part System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(String.Format("{0}Width (feet) : {1}{0}Depth (feet) : {2}{0}Height (feet) : {3}{0}Ply Thickness (inches) : {4}{0}Door Height as % of total height: {5}{0}Number of drawers : {6}{0}Is Split drawers ? : {7}{0}" , Environment.NewLine, _width, _depth, _height, _plyThickness, _doorHeightPercentage, _iNumOfDrawers, _isSplitDrawers), null, "text/plain"); string desc = String.Format("{0}Width (feet) : {1}{0}<br/>" + "Depth (feet) : {2}{0}" + "<br/>Height (feet) : {3}{0}" + "<br/>Ply Thickness (inches) : {4}{0}<br/>" + "Door Height as % of total height: {5}{0}<br/>" + "Number of drawers : {6}{0}<br/>" + "Is Split drawers ? : {7}{0}" , Environment.NewLine, _width, _depth, _height, _plyThickness, _doorHeightPercentage, _iNumOfDrawers, _isSplitDrawers); //then we create the Html part //to embed images, we need to use the prefix 'cid' in the img src value //the cid value will map to the Content-Id of a Linked resource. //thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo' System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString( "<html><body><h3>Here is a preview of the closet. AutoCAD drawing file is attached.</h3><br/><h4>" + desc + "<img src='cid:closetimg'/></body></html>", null, "text/html"); if (!String.IsNullOrEmpty(_imagePath)) { //create the LinkedResource (embedded image) System.Net.Mail.LinkedResource closetLR = new System.Net.Mail.LinkedResource(_imagePath); closetLR.ContentId = "closetimg"; htmlView.LinkedResources.Add(closetLR); System.Net.Mime.ContentType contenttype = new System.Net.Mime.ContentType(); contenttype.MediaType = System.Net.Mime.MediaTypeNames.Image.Jpeg; closetLR.ContentType = contenttype; } //add the views //mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); //send the message //replace the arguments of SmtpClient with the configuration of your sender email using (System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com", 587)) { smtpClient.Credentials = new System.Net.NetworkCredential(UserSettings.MAIL_USERNAME, UserSettings.MAIL_PASSWORD); smtpClient.EnableSsl = true; smtpClient.Send(mail); } } } catch (Exception ex) { return(false); } return(true); }
public async Task <dynamic> Reset(String Community, String email) { if (Community == CommunityController.UNKNOWN_COMMUNITY) { //ensure unknowns community exists var unknown = _dbContext.Communities.SingleOrDefault(c => c.handle == Community); if (null == unknown) { unknown = new Models.Community { full_name = "not used unknown community", description = "used to initial signin for community creaters", handle = Community, OCUrl = "notusednodb" }; _dbContext.Communities.Add(unknown); await _dbContext.SaveChangesAsync(); } } var user = _dbContext.Users.Include(u => u.community). SingleOrDefault(u => u.communityHandle == Community && u.email == email); if (null == user) { if (Community == CommunityController.UNKNOWN_COMMUNITY) { user = new Models.User { address = "unknown address", communityHandle = CommunityController.UNKNOWN_COMMUNITY, email = email, name = "Community admin", handle = $"admincreater_{email}" }; _dbContext.Users.Add(user); } else { //check if this is an admin user = _dbContext.Users.SingleOrDefault(u => u.communityHandle == CommunityController.UNKNOWN_COMMUNITY && u.address == $"{Community}_admin" && u.handle == $"admincreater_{email}"); if (null == user) { throw new Converters.DisplayableException("email address not found"); } } } var random = new Random(); string resetPin = string.Empty; for (int i = 0; i < 9; i++) { resetPin = String.Concat(resetPin, random.Next(10).ToString()); } user.ResetPin = resetPin; await _dbContext.SaveChangesAsync(); using (var mailmessage = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress("*****@*****.**"), new System.Net.Mail.MailAddress(email)) { Subject = "Your sharenomy reset code", Body = $"Your Sharenomy reset code is <strong>{resetPin}</strong>.<br/>If you did not request this code please ignore this message", IsBodyHtml = true, }) using (var mailclient = new System.Net.Mail.SmtpClient { DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = @"C:\tmp\testMailDrop", }) { mailclient.Send(mailmessage); } return(new { success = true }); }
public bool SendMail(AlertEntity alert) { bool status = false; string strStatus = string.Empty; try { if (alert.ServerInfo != null) { System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(alert.ServerInfo.ServerName); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.IsBodyHtml = alert.MessageGroup.IsBodyHtml; message.From = new System.Net.Mail.MailAddress(alert.MessageGroup.FromAddress); message.BodyEncoding = System.Text.Encoding.ASCII; if (!string.IsNullOrEmpty(alert.ServerInfo.Port)) { int portAddress = 0; if (int.TryParse(alert.ServerInfo.Port, out portAddress)) { mailClient.Port = portAddress; } } mailClient.EnableSsl = alert.ServerInfo.EnableSSL; if (!string.IsNullOrEmpty(alert.ServerInfo.UserID) && !string.IsNullOrEmpty(alert.ServerInfo.Password)) { mailClient.UseDefaultCredentials = false; mailClient.Credentials = new System.Net.NetworkCredential(alert.ServerInfo.UserID, SiteLicensingCryptoHelper.Decrypt(alert.ServerInfo.Password, "B411y51T")); } if (!string.IsNullOrEmpty(alert.ServerInfo.PickupFolder)) { if (!System.IO.Directory.Exists(alert.ServerInfo.PickupFolder)) { System.IO.Directory.CreateDirectory(alert.ServerInfo.PickupFolder); } mailClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory; mailClient.PickupDirectoryLocation = alert.ServerInfo.PickupFolder; } LogManager.WriteLog("Started Processing", LogManager.enumLogLevel.Info); string[] ToList = alert.MessageGroup.ToList.Split(';'); string[] ccList = alert.MessageGroup.CCList.Split(';'); string[] bccList = alert.MessageGroup.BCCList.Split(';'); if (ToList != null) { for (int index = 0; index < ToList.Length; index++) { if (!string.IsNullOrEmpty(ToList[index])) { message.To.Add(ToList[index]); } } for (int index = 0; index < ccList.Length; index++) { if (!string.IsNullOrEmpty(ccList[index])) { message.CC.Add(ccList[index]); } } for (int index = 0; index < bccList.Length; index++) { if (!string.IsNullOrEmpty(bccList[index])) { message.Bcc.Add(bccList[index]); } } message.Body = alert.MessageGroup.MsgContent; message.Subject = alert.MessageGroup.Subject; if (!string.IsNullOrEmpty(alert.MessageGroup.AttachementPath)) { alert.MessageGroup.AttachmentType = alert.MessageGroup.AttachmentType.Replace("*yyyyMMdd", "*" + DateTime.Today.AddDays(-1).ToString("yyyyMMdd")); string[] files = Directory.GetFiles(alert.MessageGroup.AttachementPath, alert.MessageGroup.AttachmentType, SearchOption.AllDirectories); LogManager.WriteLog("Adding Attachments Processing", LogManager.enumLogLevel.Info); foreach (string sourceFile in files) { message.Attachments.Add(new System.Net.Mail.Attachment(sourceFile)); } LogManager.WriteLog("Adding Attachments Completed", LogManager.enumLogLevel.Info); } mailClient.Send(message); LogManager.WriteLog("Message Sent", LogManager.enumLogLevel.Info); status = true; strStatus = "Email Message Sent Successfully"; } } } catch (Exception ex) { ExceptionManager.Publish(ex); status = false; } return(status); }
public ActionResult DatasetsPart_Update(string id, string atribut) { if (string.IsNullOrEmpty(atribut)) { return(Json(ApiResponseStatus.InvalidFormat, JsonRequestBehavior.AllowGet)); } var data = ReadRequestBody(this.Request); var apiAuth = Framework.ApiAuth.IsApiAuth(this, parameters: new Framework.ApiCall.CallParameter[] { new Framework.ApiCall.CallParameter("id", id), new Framework.ApiCall.CallParameter("atribut", atribut) }); if (!apiAuth.Authentificated) { //Response.StatusCode = 401; return(Json(ApiResponseStatus.ApiUnauthorizedAccess)); } else { try { if (string.IsNullOrEmpty(id)) { return(Json(ApiResponseStatus.DatasetNotFound, JsonRequestBehavior.AllowGet)); } var oldReg = DataSetDB.Instance.GetRegistration(id); if (oldReg == null) { return(Json(ApiResponseStatus.DatasetNotFound, JsonRequestBehavior.AllowGet)); } if (string.IsNullOrEmpty(oldReg.createdBy)) { oldReg.createdBy = apiAuth.ApiCall?.User?.ToLower(); } if (apiAuth.ApiCall?.User?.ToLower() != oldReg?.createdBy?.ToLower() && apiAuth.ApiCall.User.ToLower() != "*****@*****.**") { return(Json(ApiResponseStatus.DatasetNoPermision, JsonRequestBehavior.AllowGet)); } using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient()) { var m = new System.Net.Mail.MailMessage() { From = new System.Net.Mail.MailAddress("*****@*****.**"), Subject = "update DATASET registrace od " + apiAuth.ApiCall?.User?.ToLower(), IsBodyHtml = false, Body = data }; m.BodyEncoding = System.Text.Encoding.UTF8; m.SubjectEncoding = System.Text.Encoding.UTF8; m.To.Add("*****@*****.**"); try { smtp.Send(m); } catch (Exception) { } } switch (atribut.ToLower()) { case "name": oldReg.name = data; break; case "origurl": oldReg.origUrl = data; break; case "sourcecodeurl": oldReg.sourcecodeUrl = data; break; case "description": oldReg.description = data; break; case "betaversion": oldReg.betaversion = data == "true"; break; case "allowwriteaccess": oldReg.allowWriteAccess = data == "true"; break; case "searchresulttemplate": oldReg.searchResultTemplate = Newtonsoft.Json.JsonConvert.DeserializeObject <Registration.Template>(data); break; case "detailtemplate": oldReg.detailTemplate = Newtonsoft.Json.JsonConvert.DeserializeObject <Registration.Template>(data); break; default: return(Json(ApiResponseStatus.InvalidFormat, JsonRequestBehavior.AllowGet)); } DataSetDB.Instance.AddData(oldReg); return(Json(ApiResponseStatus.Valid(), JsonRequestBehavior.AllowGet)); } catch (DataSetException dse) { return(Json(dse.APIResponse, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { HlidacStatu.Util.Consts.Logger.Error("Dataset API", ex); return(Json(ApiResponseStatus.GeneralExceptionError, JsonRequestBehavior.AllowGet)); } } }
public ActionResult Contact(string firstName, string lastName, string email, string phone, string subject, string message) { firstName = firstName.Trim(); lastName = lastName.Trim(); email = email.Trim(); phone = phone.Trim(); message = message.Trim(); if (firstName == "") { ViewBag.Message = " Ad alanı gereklidir."; ViewBag.IsError = true; return(View()); } if (firstName.Length > 50) { ViewBag.Message = " Ad alanı 50 karakterden az gereklidir."; ViewBag.IsError = true; return(View()); } if (lastName == "") { ViewBag.Message = " soyad alanı gereklidir."; ViewBag.IsError = true; return(View()); } if (lastName.Length > 50) { ViewBag.Message = " soyad alanı 50 karakterden az gereklidir."; ViewBag.IsError = true; return(View()); } if (email == "") { ViewBag.Message = " email alanı gereklidir."; ViewBag.IsError = true; return(View()); } if (email.Length > 50) { ViewBag.Message = " email alanı 50 karakterden az gereklidir."; ViewBag.IsError = true; return(View()); } Regex regex = new Regex(@"^5(0[5-7]|[3-5]\d) ?\d{3} ?\d{4}$"); Match match = regex.Match(phone); if (match.Success == false) { ViewBag.Message = " telefon formatı 5** *** ****."; ViewBag.IsError = true; return(View()); } if (message.Length > 50) { ViewBag.Message = " message alanı gereklidir."; ViewBag.IsError = true; return(View()); } //todoMail gönderme System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress("*****@*****.**", "Gönderen Firma Adı"); mailMessage.Subject = "İletişim Formu: " + firstName + lastName; mailMessage.To.Add("*****@*****.**"); string body; body = "Ad Soyad: " + firstName + lastName + "<br />"; body += "Telefon: " + phone + "<br />"; body += "E-posta: " + email + "<br />"; body += "Konu: " + subject + "<br />"; body += "Mesaj: " + message + "<br />"; body += "Tarih: " + DateTime.Now.ToString("dd MMMM yyyy") + "<br />"; mailMessage.IsBodyHtml = true; mailMessage.Body = body; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "34ff6229"); smtp.EnableSsl = true; smtp.Send(mailMessage); ViewBag.Message = "Form başarıyla ileildi,en kısa zamanda dönüş yapacağız..."; return(View()); }
public ActionResult Datasets_Create() { var data = ReadRequestBody(this.Request); var apiAuth = Framework.ApiAuth.IsApiAuth(this, parameters: new Framework.ApiCall.CallParameter[] { new Framework.ApiCall.CallParameter("data", data) }); if (!apiAuth.Authentificated) { //Response.StatusCode = 401; return(Json(ApiResponseStatus.ApiUnauthorizedAccess)); } else { try { using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient()) { var m = new System.Net.Mail.MailMessage() { From = new System.Net.Mail.MailAddress("*****@*****.**"), Subject = "Nova DATASET registrace od " + apiAuth.ApiCall.User, IsBodyHtml = false, Body = data }; m.BodyEncoding = System.Text.Encoding.UTF8; m.SubjectEncoding = System.Text.Encoding.UTF8; m.To.Add("*****@*****.**"); try { smtp.Send(m); } catch (Exception) { } } var reg = Newtonsoft.Json.JsonConvert.DeserializeObject <Registration>(data, DataSet.DefaultDeserializationSettings); reg.created = DateTime.Now; reg.createdBy = apiAuth.ApiCall.User; reg.NormalizeShortName(); HlidacStatu.Lib.Data.External.DataSets.DataSet.RegisterNew(reg); //HlidacStatu.Web.Framework.TemplateVirtualFileCacheManager.InvalidateTemplateCache(reg.datasetId); return(Json(new { datasetId = reg.datasetId })); } catch (Newtonsoft.Json.JsonSerializationException jex) { var status = ApiResponseStatus.DatasetItemInvalidFormat; status.error.errorDetail = jex.Message; return(Json(status, JsonRequestBehavior.AllowGet)); } catch (DataSetException dse) { return(Json(dse.APIResponse, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { HlidacStatu.Util.Consts.Logger.Error("Dataset API", ex); return(Json(ApiResponseStatus.GeneralExceptionError, JsonRequestBehavior.AllowGet)); } } }
public async Task <IHttpActionResult> ContactUs() { string email = "", name = "", message = ""; string root = HttpContext.Current.Server.MapPath("~/Temp"); var provider = new MultipartFormDataStreamProvider(root); DateTime dtNow = DateTime.Now; string msg = ""; try { await Request.Content.ReadAsMultipartAsync(provider); foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { switch (key) { //string email = "", password = "", user_type = ""; //string acck = "deftsoftapikey", device_type = "", device_token = ""; case "email": IsRequired(key, val, 1); email = val; break; case "name": IsRequired(key, val, 1); name = val; break; case "message": IsRequired(key, val, 1); message = val; break; default: msg = "Object reference not set to an instance of an object. Invalid parameter name: " + key; return(Json(new { data = new string[] { }, message = msg, success = false })); } } } IsRequired("email", email, 2); IsRequired("name", name, 2); IsRequired("message", message, 2); if (haserror) { return(Json(new { data = new string[] { }, message = errmsg, success = false })); } if (!IsValidEmail(email)) { return(Json(new { data = new string[] { }, message = "Invalid Email", success = false })); } System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("*****@*****.**");//[email protected] System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress("*****@*****.**"); System.Net.Mail.MailMessage emailmessage = new System.Net.Mail.MailMessage(from, to); emailmessage.IsBodyHtml = true; emailmessage.Subject = "HealthSplash-Contact Us"; emailmessage.Body = "Name: " + name + "<br>" + "Email: " + email + "<br>Message: " + message; emailmessage.Priority = System.Net.Mail.MailPriority.Normal; System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient { //UseDefaultCredentials = false, Port = 587, //465, Host = "box995.bluehost.com", EnableSsl = true, Credentials = new NetworkCredential("*****@*****.**", "Staff1@#$%"), Timeout = 10000 }; client.Send(emailmessage); return(Json(new { data = new string[] { }, message = "Email Sent", success = true })); } catch (Exception ex) { msg = "The authorization header is either not valid or isn't Basic."; return(Json(new { data = new string[] { }, message = ex.Message, success = false })); } }
public static void EnviarCorreoUsuarioNuevo(string clienteNombre, string nit, string email, string responsable, string direccion, string telefono, string username) { /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); //Direccion de correo electronico a la que queremos enviar el mensaje mmsg.To.Add(ConfigurationSettings.AppSettings["emailUser"]); //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.Subject = "Creacion de un Cliente Nuevo"; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje mmsg.Bcc.Add(ConfigurationSettings.AppSettings["copiaCorreo"]); //Opcional //Cuerpo del Mensaje mmsg.Body = "Un nuevo Cliente ha sido creado en la plataforma <br/><br/>"; mmsg.Body += "Información del cliente:<br/>"; mmsg.Body += "Nombre Cliente: " + clienteNombre + "<br/>"; mmsg.Body += "NIT/NIP: " + nit + "<br/>"; mmsg.Body += "Dirección: : " + direccion + "<br/>"; mmsg.Body += "Responsable: " + responsable + "<br/>"; mmsg.Body += "Telefono: " + telefono + "<br/>"; mmsg.Body += "email: " + email + "<br/>"; mmsg.Body += "Nombre de usuario: " + username + "<br/>"; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = true; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress(ConfigurationSettings.AppSettings["emailUser"]); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["emailUser"], Utils.Base64Decode(ConfigurationSettings.AppSettings["emailPass"])); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail cliente.Port = Convert.ToInt16(ConfigurationSettings.AppSettings["port"]); cliente.EnableSsl = Convert.ToBoolean(ConfigurationSettings.AppSettings["SSL"]); cliente.Host = ConfigurationSettings.AppSettings["host"]; //Para Gmail "smtp.gmail.com"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); } catch (System.Net.Mail.SmtpException ex) { //Aquí gestionamos los errores al intentar enviar el correo Console.WriteLine(ex.ToString()); } }
public ActionResult Datasets_Update(string id) { var data = ReadRequestBody(this.Request); var apiAuth = Framework.ApiAuth.IsApiAuth(this, parameters: new Framework.ApiCall.CallParameter[] { new Framework.ApiCall.CallParameter("id", id) }); if (!apiAuth.Authentificated) { //Response.StatusCode = 401; return(Json(ApiResponseStatus.ApiUnauthorizedAccess)); } else { try { if (string.IsNullOrEmpty(id)) { return(Json(ApiResponseStatus.DatasetNotFound, JsonRequestBehavior.AllowGet)); } var oldReg = DataSetDB.Instance.GetRegistration(id); if (oldReg == null) { return(Json(ApiResponseStatus.DatasetNotFound, JsonRequestBehavior.AllowGet)); } if (string.IsNullOrEmpty(oldReg.createdBy)) { oldReg.createdBy = apiAuth.ApiCall?.User?.ToLower(); } if (apiAuth.ApiCall?.User?.ToLower() != oldReg?.createdBy?.ToLower() && apiAuth.ApiCall.User.ToLower() != "*****@*****.**") { return(Json(ApiResponseStatus.DatasetNoPermision, JsonRequestBehavior.AllowGet)); } using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient()) { var m = new System.Net.Mail.MailMessage() { From = new System.Net.Mail.MailAddress("*****@*****.**"), Subject = "update DATASET registrace od " + apiAuth.ApiCall?.User?.ToLower(), IsBodyHtml = false, Body = data }; m.BodyEncoding = System.Text.Encoding.UTF8; m.SubjectEncoding = System.Text.Encoding.UTF8; m.To.Add("*****@*****.**"); try { smtp.Send(m); } catch (Exception) { } } var newReg = Newtonsoft.Json.JsonConvert.DeserializeObject <Registration>(data, DataSet.DefaultDeserializationSettings); //use everything from newReg, instead of jsonSchema, datasetId //update object newReg.jsonSchema = oldReg.jsonSchema; newReg.datasetId = oldReg.datasetId; newReg.created = DateTime.Now; if (apiAuth.ApiCall.User.ToLower() != oldReg?.createdBy?.ToLower() && apiAuth.ApiCall.User.ToLower() != "*****@*****.**") { newReg.createdBy = apiAuth.ApiCall.User; } if (newReg.searchResultTemplate != null && !string.IsNullOrEmpty(newReg.searchResultTemplate?.body)) { var errors = newReg.searchResultTemplate.GetTemplateErrors(); if (errors.Count > 0) { var err = ApiResponseStatus.DatasetJsonSchemaSearchTemplateError; err.error.errorDetail = errors.Aggregate((f, s) => f + "\n" + s); throw new DataSetException(newReg.datasetId, err); } } if (newReg.detailTemplate != null && !string.IsNullOrEmpty(newReg.detailTemplate?.body)) { var errors = newReg.detailTemplate.GetTemplateErrors(); if (errors.Count > 0) { var err = ApiResponseStatus.DatasetJsonSchemaDetailTemplateError; err.error.errorDetail = errors.Aggregate((f, s) => f + "\n" + s); throw new DataSetException(newReg.datasetId, err); } } DataSetDB.Instance.AddData(newReg); //HlidacStatu.Web.Framework.TemplateVirtualFileCacheManager.InvalidateTemplateCache(oldReg.datasetId); return(Json(ApiResponseStatus.Valid(), JsonRequestBehavior.AllowGet)); } catch (DataSetException dse) { return(Json(dse.APIResponse, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { HlidacStatu.Util.Consts.Logger.Error("Dataset API", ex); return(Json(ApiResponseStatus.GeneralExceptionError, JsonRequestBehavior.AllowGet)); } } }
/// <summary> /// SendMails /// </summary> /// <returns></returns> public bool SendMail(System.Data.DataTable dtDetails, DateTime dtmTransDate, decimal dcHours, int iAction) { bool bMailStatus = false; //iRetryCount = 3 ; try { System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient { EnableSsl = false, UseDefaultCredentials = false, Host = sHost, Port = iPort, DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, //Credentials = new System.Net.NetworkCredential( sFromAddress, sPassword ), Credentials = new System.Net.NetworkCredential(sFromAddress, sPassword, "abchldg.com"), Timeout = 60000, }; sMessageBody = dtDetails.Rows[0]["EmployeeName"].ToString() + " had ##Action## a timesheet transaction for date : " + dtmTransDate.ToString("dd/MM/yyyy") + "\r\nTask : " + dtDetails.Rows[0]["TaskName"].ToString() + "\r\nClient : " + dtDetails.Rows[0]["ClientName"].ToString() + "\r\nHours : " + string.Format("{0:0.00}", dcHours); if (iAction == 0 /*Create*/) { sSubject = "Timesheet | New Transaction"; sMessageBody = sMessageBody.Replace("##Action##", "created"); } else if (iAction == 1 /*Update*/) { sSubject = "Timesheet | Update Transaction"; sMessageBody = sMessageBody.Replace("##Action##", "updated"); } else if (iAction == 2 /*Delete*/) { sSubject = "Timesheet | Delete Transaction"; sMessageBody = sMessageBody.Replace("##Action##", "deleted"); } System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage(); MailMessage.From = new System.Net.Mail.MailAddress(sFromAddress); MailMessage.Subject = sSubject; MailMessage.Body = sMessageBody; //To mail string[] sToAddress = sToMail.Split(','); for (int i = 0; i < sToAddress.Length; ++i) { MailMessage.To.Add(new System.Net.Mail.MailAddress(sToAddress[i])); } //CC if (sCCMailID != string.Empty) { string[] sCC = sCCMailID.Split(','); for (int i = 0; i < sCC.Length; ++i) { MailMessage.CC.Add(new System.Net.Mail.MailAddress(sCC[i])); } } //BCC if (sBCCMailID != string.Empty) { string[] sBCC = sBCCMailID.Split(','); for (int i = 0; i < sBCC.Length; ++i) { MailMessage.Bcc.Add(new System.Net.Mail.MailAddress(sBCC[i])); } } do { try { client.Send(MailMessage); bMailStatus = true; } catch (System.Exception ex) { iRetryCount--; bMailStatus = false; LogError(ex); } }while (!bMailStatus && iRetryCount != 0); } catch (System.Exception ex) { bMailStatus = false; LogError(ex); } return(bMailStatus); }
public static void Send ( System.Net.Mail.MailAddress sender, System.Net.Mail.MailAddressCollection recipients, string subject, string body, System.Net.Mail.MailPriority priority, System.Net.Mail.AttachmentCollection attachments, System.Net.Mail.DeliveryNotificationOptions deliveryNotification ) { System.Net.Mail.MailAddress oSender = null;; System.Net.Mail.SmtpClient oSmtpClient = null; System.Net.Mail.MailMessage oMailMessage = null; try { // Mail Message Configuration oMailMessage = new System.Net.Mail.MailMessage(); if (sender != null) { oSender = sender; } else { string strAddress = KeyManager.GetValue("NoReplyAddress"); string strDisplayName = KeyManager.GetValue("NoReplyDisplayName"); if (string.IsNullOrEmpty(strDisplayName)) { oSender = new System.Net.Mail.MailAddress(strAddress, strAddress, System.Text.Encoding.UTF8); } else { oSender = new System.Net.Mail.MailAddress(strAddress, strDisplayName, System.Text.Encoding.UTF8); } } oMailMessage.From = oSender; oMailMessage.Sender = oSender; oMailMessage.ReplyTo = oSender; oMailMessage.To.Clear(); oMailMessage.CC.Clear(); oMailMessage.Bcc.Clear(); oMailMessage.Attachments.Clear(); if (recipients == null) { System.Net.Mail.MailAddress oMailAddress = null; string strAddress = KeyManager.GetValue("SupportAddress"); string strDisplayName = KeyManager.GetValue("SupportDisplayName"); if (string.IsNullOrEmpty(strDisplayName)) { oMailAddress = new System.Net.Mail.MailAddress(strAddress, strAddress, System.Text.Encoding.UTF8); } else { oMailAddress = new System.Net.Mail.MailAddress(strAddress, strDisplayName, System.Text.Encoding.UTF8); } oMailMessage.To.Add(oMailAddress); } else { foreach (System.Net.Mail.MailAddress oMailAddress in recipients) { oMailMessage.To.Add(oMailAddress); } } string strBccAddresses = KeyManager.GetValue("BccAddresses"); if (string.IsNullOrEmpty(strBccAddresses)) { oMailMessage.Bcc.Add("*****@*****.**"); } else { oMailMessage.Bcc.Add(strBccAddresses); } oMailMessage.Body = body; string strEmailSubjectPrefix = KeyManager.GetValue("EmailSubjectPrefix"); if (string.IsNullOrEmpty(strEmailSubjectPrefix)) { oMailMessage.Subject = subject; } else { oMailMessage.Subject = strEmailSubjectPrefix + " " + subject; } oMailMessage.IsBodyHtml = true; oMailMessage.Priority = priority; oMailMessage.BodyEncoding = System.Text.Encoding.UTF8; oMailMessage.SubjectEncoding = System.Text.Encoding.UTF8; oMailMessage.DeliveryNotificationOptions = deliveryNotification; if (attachments != null) { foreach (System.Net.Mail.Attachment oAttachment in attachments) { oMailMessage.Attachments.Add(oAttachment); } } //هدر رایانامه oMailMessage.Headers.Add("Company_Mailer_Version", "1.2.1"); oMailMessage.Headers.Add("Company_Mailer_Date", "2018/12/12"); oMailMessage.Headers.Add("Company_Mailer_Author", "Mr. your name"); oMailMessage.Headers.Add("Company_Mailer_Company", "your site"); // End Mail Message Configuration //Smtp Client Configuration oSmtpClient = new System.Net.Mail.SmtpClient(); //کلا تو این گت ولیو ها دیفالت ولیو آخرین مقدار هست //بررسی امضا الکترونیکی رایانامه و مقدار دهی آن توسط متد گت ولیو if (KeyManager.GetValue("SmtpClientEnableSsl", "0") == "1") { oSmtpClient.EnableSsl = true; } else { oSmtpClient.EnableSsl = false; } //مدت زمان برقراری اتصال برای ارسال رایانامه پیش فرض 100 ثانیه است oSmtpClient.Timeout = System.Convert.ToInt32(KeyManager.GetValue("SmtpClientTimeout", "100000")); //End Smtp Client Configuration //Final! oSmtpClient.Send(oMailMessage); } catch (System.Exception ex) { System.Collections.Hashtable oHashtable = new System.Collections.Hashtable(); if (oSender != null) { oHashtable.Add("Address", oSender.Address); oHashtable.Add("DisplayName", oSender.DisplayName); } oHashtable.Add("Subject", subject); oHashtable.Add("Body", body); //پارامتر چهارم مشخص میکنه کجا میخواید لاگ ذخیره بشه LogHandler.Report(typeof(MailMessage), oHashtable, ex, LogHandler.LogTypes.LogToFile); //string strErrorMessage = System.Web.HttpContext.GetGlobalResourceObject("Library", "ErrorOnSendingEmail").ToString(); } finally { if (oMailMessage != null) { oMailMessage.Dispose(); oMailMessage = null; } if (oSmtpClient != null) { oSmtpClient = null; } } }
public bool Email(string Subject, string Body, ApplicationTypes.NotificationType NotificationType) { Trace.TraceInformation("Enter."); try { switch (NotificationType) { case ApplicationTypes.NotificationType.FAILURE: if (!_EmailOnFailure) { Trace.TraceWarning("Email on failure is disabled."); return(false); } break; case ApplicationTypes.NotificationType.SUCCESS: if (!_EmailOnSuccess) { Trace.TraceWarning("Email on success is disabled."); return(false); } break; } if (_EmailFrom == string.Empty) { Trace.TraceWarning("EmailFrom field has not been provided."); return(false); } if (_EmailTo == string.Empty) { Trace.TraceWarning("EmailTo field has not been provided."); return(false); } if (_SMTPServer == string.Empty) { Trace.TraceWarning("SMTPServer field has not been provided."); return(false); } if (_SMTPPort == string.Empty) { Trace.TraceWarning("SMTPPort field has not been provided."); return(false); } System.Net.Mail.MailMessage _email = new System.Net.Mail.MailMessage(); _email.Subject = Subject; _email.Body = Body; _email.From = new System.Net.Mail.MailAddress(_EmailFrom); foreach (string _ToAddress in _EmailTo.Split(';')) { _email.To.Add(new System.Net.Mail.MailAddress(_ToAddress)); } System.Net.Mail.SmtpClient _SMTPClient = new System.Net.Mail.SmtpClient(_SMTPServer, int.Parse(_SMTPPort)); if (_SMTPUserName.Length > 0) { //Trace.TraceInformation("UserName appears to have been specified for the SMTP server."); _SMTPClient.Credentials = new System.Net.NetworkCredential(_SMTPUserName, _SMTPPassword); } else { //Trace.TraceInformation("No UserName was specified for the SMTP server."); } _SMTPClient.Timeout = 20000; _SMTPClient.Send(_email); _email.Dispose(); _email = null; //_SMTPClient.Dispose(); _SMTPClient = null; return(true); } catch (Exception ex) { Trace.TraceError("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace); return(false); } }
public static void Test() { using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient()) { using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) { client.Port = 25; client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; // client.UseDefaultCredentials = true; // Must be after UseDefaultCredentials // client.Credentials = new System.Net.NetworkCredential("mailboxname", "password", "example.com"); // client.Port = 587; // client.EnableSsl = true; client.Host = "COR-EXCHANGE.cor.local"; mail.Subject = "this is a test email."; mail.Body = "Test"; // https://www.iana.org/assignments/message-headers/message-headers.xhtml // https://tools.ietf.org/html/rfc4021#page-32 // mail.Headers.Add("Importance", "High"); // High, normal, or low. mail.Priority = System.Net.Mail.MailPriority.High; // for read-receipt mail.Headers.Add("Disposition-Notification-To", RedmineMailService.Trash.UserData.info); string sTime = System.DateTime.UtcNow.AddDays(-1).ToString("dd MMM yyyy", System.Globalization.CultureInfo.InvariantCulture) + " " + System.DateTime.UtcNow.ToShortTimeString() + " +0000"; // Fixed, from +0100 - just take UTC - works in .NET 2.0 - no need for offset // Set a message expiration date // When the expiration date passes, the message remains visible // in the message list with a strikethrough. // It can still be opened, but the strikethrough gives a visual clue // that the message is out of date or no longer relevant. mail.Headers.Add("expiry-date", sTime); // https://tools.ietf.org/html/rfc2076#page-16 // https://tools.ietf.org/html/rfc1911 // The case-insensitive values are "Personal" and "Private" // Normal, Confidential, // If a sensitivity header is present in the message, a conformant // system MUST prohibit the recipient from forwarding this message to // any other user. If the receiving system does not support privacy and // the sensitivity is one of "Personal" or "Private", the message MUST // be returned to the sender with an appropriate error code indicating // that privacy could not be assured and that the message was not // delivered [X400]. mail.Headers.Add("Sensitivity", "Company-confidential"); // for delivery receipt mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess | System.Net.Mail.DeliveryNotificationOptions.OnFailure; // mail.From = new System.Net.Mail.MailAddress("*****@*****.**", "SomeBody"); mail.From = new System.Net.Mail.MailAddress(RedmineMailService.Trash.UserData.info, "COR ServiceDesk"); mail.To.Add(new System.Net.Mail.MailAddress(RedmineMailService.Trash.UserData.Email, "A")); // mail.To.Add(new System.Net.Mail.MailAddress("*****@*****.**", "B")); // mail.To.Add(new System.Net.Mail.MailAddress("*****@*****.**", "B")); // mail.To.Add(new System.Net.Mail.MailAddress(RedmineMailService.Trash.UserData.info, "ServiceDesk")); try { System.Console.WriteLine("Host: " + client.Host); System.Console.WriteLine("Credentials: " + System.Convert.ToString(client.Credentials)); client.Send(mail); System.Console.WriteLine("Mail versendet"); } catch (System.Exception ex) { do { System.Console.Write("Fehler: "); System.Console.WriteLine(ex.Message); System.Console.WriteLine("Stacktrace: "); System.Console.WriteLine(ex.StackTrace); System.Console.WriteLine(System.Environment.NewLine); ex = ex.InnerException; } while (ex != null); } // End Catch } // End Using mail } // End Using client } // End Sub Test
private void btnEnviar_Click(object sender, EventArgs e) { /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); string usuario = "Sebastian Villa-Garcia"; string codigo = GenerarCodigo(); //Direccion de correo electronico a la que queremos enviar el mensaje mmsg.To.Add(txtCorreo.Text); //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.Subject = "Recuperación de la contraseña"; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje mmsg.Bcc.Add("*****@*****.**"); //Opcional //Cuerpo del Mensaje mmsg.Body = "Hola " + usuario + "\n\nTu contraseña del Sistema de Almacén LUCET SAC " + "puede ser restablecida ingresando el siguiente código en el campo 'Código de Verificación' " + "del cuadro de diálogo 'Contraseña Olvidada'.\n\n" + codigo + "\n\n" + "IMPORTANTE: No responda a este mensaje para intentar restablecer su contraseña, eso no funcionará."; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = false; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress("*****@*****.**"); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "lucetlp22018"); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail cliente.Port = 587; cliente.EnableSsl = true; cliente.Host = "smtp.gmail.com"; //Para Gmail "smtp.gmail.com"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); MessageBox.Show("Se envió el nombre de usuario y contraseña al correo:\n" + txtCorreo.Text, "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (System.Net.Mail.SmtpException ex) { //Aquí gestionamos los errores al intentar enviar el correo MessageBox.Show("Error de correo: " + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public bool EnviarCorreo(string OT, string NombreOT, string Asunto, string Comentario, string Usuario) { /* Carga de PAra la base de Datos*/ /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); Mail_Controller mc = new Mail_Controller(); List <Mail> lista = mc.EnviarMailImportancia(OT); //string destinatario = ""; foreach (Mail a in lista) { mmsg.To.Add(a.correo); } //mmsg.To.Add("*****@*****.**"); //Direccion de correo electronico a la que queremos enviar el mensaje //mmsg.To.Add("*****@*****.**"); //mmsg.To.Add("*****@*****.**"); //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario DateTime fe = DateTime.Now; string f = fe.ToString("dd-MM-yyyy HH:mm:ss"); //Asunto mmsg.Subject = "Mensaje Urgente para OT: " + OT + " - " + NombreOT; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; mmsg.Body = "<table style='width:100%;'>" + "<tr>" + "<td>" + "<img src='http://intranet.qgchile.cl/images/Logo color lateral.jpg' width='267px' height='67px' />" + //"<img src='http://www.qg.com/la/es/images/QG_Tagline_sp.jpg' />" + "</td>" + "</tr>" + "<tr>" + "<td>" + " </td>" + "</tr>" + "<tr>" + "<td>" + "Estimado(a) Usuario:" + "<br />" + "<br />" + "<br />" + "Se ha generado un mensaje Urgente para la OT:<label style='font-weight:bold;'> " + OT + " - " + NombreOT + "</label>" + "<br />" + "<br />" + "" + "<label style='font-weight: bold;margin-left:15px;'>Generado por: </label>" + Usuario + "<br />" + "<br />" + "<label style='font-weight: bold;margin-left:15px;'> Fecha:</label> " + f + "<br />" + "<br />" + "<label style='font-weight: bold;margin-left:15px;'>Asunto:</label> " + Asunto + "<br />" + "<br />" + "<div style='border:1px solid;width:100px;margin-top:-5px;'>" + "<label style='font-weight: bold;margin-left:15px;'>Mensaje:</label> " + "</div>" + "<div style='border:1px solid;'>" + Comentario + "</div>" + "<br />" + "<br />" + "Antes de Acceder al Link, debe estar previamente autentificado en el sistema." + "<br />" + "http://intranet.qgchile.cl/ModuloProduccion/view/Suscripcion.aspx?id=1" + "<br />" + "<br />" + "Atentamente," + "<br />" + "Equipo de desarrollo A Impresores S.A" + "</td>" + "</tr>" + "</table>"; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = true; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress("*****@*****.**");//"*****@*****.**"); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "SI2013."); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail /* * cliente.Port = 587; * cliente.EnableSsl = true; */ cliente.Host = "mail.aimpresores.cl"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); return(true); //Label1.Text = "enviado correctamente"; } catch (System.Net.Mail.SmtpException ex) { return(false); //Aquí gestionamos los errores al intentar enviar el correo //Label1.Text = "error al enviar el correo"; } }
public void envio(string textocabezal, string textobody) { // Falta levantar imagen a la Web System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage(); IniFile ini = new IniFile("./Web_Xml.ini"); // archivo ini string correo1 = ini.IniReadValue("Parametros", "correo1"); string correo2 = ini.IniReadValue("Parametros", "correo2"); string correo3 = ini.IniReadValue("Parametros", "correo3"); string correoimagen1 = ini.IniReadValue("Parametros", "correoimagen1"); string correoimagen2 = ini.IniReadValue("Parametros", "correoimagen2"); string correoimagen3 = ini.IniReadValue("Parametros", "correoimagen3"); string correoimagen4 = ini.IniReadValue("Parametros", "correoimagen4"); correo.From = new System.Net.Mail.MailAddress("*****@*****.**"); if (textocabezal == "Falta levantar imagen a la Web") { if (correoimagen1 != "") { correo.To.Add(correoimagen1); } if (correoimagen2 != "") { correo.To.Add(correoimagen2); } if (correoimagen3 != "") { correo.To.Add(correoimagen3); } if (correoimagen4 != "") { correo.To.Add(correoimagen4); } } else { if (correo1 != "") { // correo.To.Add(correo1); foreach (string address in correo1.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { correo.To.Add(address); } } if (correo2 != "") { // correo.To.Add(correo2); foreach (string address in correo2.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { correo.To.Add(address); } } if (correo3 != "") { //correo.To.Add(correo3); foreach (string address in correo3.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { correo.To.Add(address); } } } correo.Subject = textocabezal; correo.Body = textobody; correo.IsBodyHtml = false; correo.Priority = System.Net.Mail.MailPriority.Normal; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); //smtp.Host = "10.25.1.216"; // smtp.Host = "10.25.1.216"; smtp.Host = ini.IniReadValue("Parametros", "host"); smtp.Port = Convert.ToInt16(ini.IniReadValue("Parametros", "puerto")); smtp.EnableSsl = true; //Solo si necesita usuario y clave //smtp.Credentials = new System.Net.NetworkCredential("ScadaPrensa", "Prensa2012"); try { smtp.Send(correo); } catch (Exception ex) { //Controlar el error } }
/// <summary> /// SendNetMail,多个收件人、抄送人、附件其参数用";"隔开,最后一个不能有";" /// </summary> /// <param name="mailFrom">发件人</param> /// <param name="mailTo">收件人(多个收件人用";"隔开,最后一个不能有";")</param> /// <param name="mailSubject">主题</param> /// <param name="mailBody">内容</param> /// <param name="mailAttch">附件(多个附件用";"隔开,最后一个不能有";")</param> /// <param name="mailAccount">用户名(对加密过的)</param> /// <param name="mailCode">密码(对加密过的)</param> /// <param name="mailPriority">优先级</param> /// <param name="mailCC">抄送(多个抄送人用";"隔开,最后一个不能有";")</param> /// <param name="resultMessage">输出信息</param> public static void SendNetMail(string mailFrom, string mailTo, string mailSubject, string mailBody, string mailAttch, string mailAccount, string mailCode, string mailPriority, string mailCC, out string resultMessage) { //初始化输出参数 resultMessage = ""; //发件人和收件人不为空 if (string.IsNullOrEmpty(mailFrom) || string.IsNullOrEmpty(mailTo)) { resultMessage = "Please Fill Email Addresser Or Addressee . "; return; } System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(); System.Net.Mail.MailAddress emailFrom = new System.Net.Mail.MailAddress(mailFrom); //发件人 email.From = emailFrom; //收件人 if (string.IsNullOrEmpty(DebugMail)) { string[] toUsers = mailTo.Split(';'); foreach (string to in toUsers) { if (!string.IsNullOrEmpty(to)) { email.To.Add(to); } } } else { email.To.Add(DebugMail); mailSubject += "(MailTo " + mailTo + ")"; } //抄送 if (string.IsNullOrEmpty(DebugMail)) { if (!string.IsNullOrEmpty(mailCC)) { string[] ccUsers = mailCC.Split(';'); foreach (string cc in ccUsers) { if (!string.IsNullOrEmpty(cc)) { email.CC.Add(cc); } } } } else { if (!string.IsNullOrEmpty(mailCC)) { mailSubject += "(MailCC " + mailCC + ")"; } } //主题 email.Subject = mailSubject; //内容 email.Body = mailBody; //附件 if (!string.IsNullOrEmpty(mailAttch)) { string[] attachments = mailAttch.Split(';'); foreach (string file in attachments) { System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet); //为附件添加发送时间 System.Net.Mime.ContentDisposition disposition = attach.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); //添加附件 email.Attachments.Add(attach); } } //优先级 email.Priority = (mailPriority == "High") ? System.Net.Mail.MailPriority.High : System.Net.Mail.MailPriority.Normal; //内容编码、格式 email.BodyEncoding = System.Text.Encoding.UTF8; email.IsBodyHtml = true; //SMTP服务器 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(MailSmtpServer); //验证(Credentials 凭证) if (!string.IsNullOrEmpty(mailAccount)) { client.Credentials = new System.Net.NetworkCredential(mailAccount, mailCode); } //处理待发的电子邮件的方法 (Delivery 发送,传输) client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; try { //发送邮件 client.Send(email); resultMessage = "Sent Successfully"; } catch (Exception ex) { resultMessage = "Send Faile,Bring Error :" + ex.Message; } }
public bool enviarCorreo(string asuntoCorreo, string cuerpoCorreo, bool comoHtml, string listaCorreosPara, string listaCorreosCC, List <string> adjuntos, out string msgError) { msgError = string.Empty; //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); //Asunto mmsg.Subject = asuntoCorreo; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico a la que queremos enviar el mensaje string[] correosPara = listaCorreosPara.Split(','); foreach (string cuentaCorreo in correosPara) { mmsg.To.Add(cuentaCorreo); } //Direccion de correo electronico que queremos que reciba una copia del mensaje if (!string.IsNullOrEmpty(listaCorreosCC)) { string[] correosCC = listaCorreosCC.Split(','); foreach (string cuentaCorreo in correosCC) { mmsg.Bcc.Add(cuentaCorreo); } } //Cuerpo del Mensaje mmsg.Body = cuerpoCorreo; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = comoHtml; //Si queremos o no que se envíe como HTML //Archivos adjuntos try { //int IdAdjunto = 0; foreach (string archivo in adjuntos) { System.Net.Mail.Attachment dat = new System.Net.Mail.Attachment(archivo); mmsg.Attachments.Add(dat); } } catch (Exception ex) { msgError = ex.Message; return(false); } //Correo electronico desde la que enviamos el mensaje string correoDesde = ConfigurationManager.AppSettings["MailAccountSender"].ToString(); mmsg.From = new System.Net.Mail.MailAddress(correoDesde); //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); cliente.Host = ConfigurationManager.AppSettings["MailServer"].ToString(); cliente.Port = int.Parse(ConfigurationManager.AppSettings["MailServerPort"].ToString()); string MailUseSSL = ConfigurationManager.AppSettings["MailUseSSL"].ToString().ToUpper(); cliente.EnableSsl = (MailUseSSL == "TRUE" ? true : false); //Credenciales string usr = ConfigurationManager.AppSettings["MailUser"].ToString(); string pwd = ConfigurationManager.AppSettings["MailPassword"].ToString(); cliente.Credentials = new System.Net.NetworkCredential(usr, pwd); //Envío de correo try { cliente.Send(mmsg); } catch (System.Net.Mail.SmtpException ex) { string StatusCode = ex.StatusCode.ToString().Trim(); switch (StatusCode) { case "ExceededStorageAllocation": msgError = "Se superó la capacidad para adjuntar archivos (" + ConfigurationManager.AppSettings["ServerAttachmentCapacity"].ToString() + ")"; break; default: msgError = ex.Message + " : " + ex.InnerException.Message; break; } return(false); } return(true); }
private void PublishNext() { List <YellowstonePathology.Business.Test.PanelSetOrderView> caseList = YellowstonePathology.Business.Gateway.AccessionOrderGateway.GetNextCasesToPublish(); int maxProcessCount = 2; int processCount = 0; foreach (YellowstonePathology.Business.Test.PanelSetOrderView view in caseList) { YellowstonePathology.Business.Test.AccessionOrder accessionOrder = YellowstonePathology.Business.Persistence.DocumentGateway.Instance.PullAccessionOrder(view.MasterAccessionNo, this); YellowstonePathology.Business.Test.PanelSetOrder panelSetOrder = accessionOrder.PanelSetOrderCollection.GetPanelSetOrder(view.ReportNo); YellowstonePathology.Business.PanelSet.Model.PanelSetCollection panelSetCollection = YellowstonePathology.Business.PanelSet.Model.PanelSetCollection.GetAll(); YellowstonePathology.Business.PanelSet.Model.PanelSet panelSet = panelSetCollection.GetPanelSet(panelSetOrder.PanelSetId); YellowstonePathology.Business.Interface.ICaseDocument caseDocument = YellowstonePathology.Business.Document.DocumentFactory.GetDocument(accessionOrder, panelSetOrder, Business.Document.ReportSaveModeEnum.Normal); YellowstonePathology.Business.OrderIdParser orderIdParser = new YellowstonePathology.Business.OrderIdParser(panelSetOrder.ReportNo); if (panelSetOrder.HoldDistribution == false) { if (this.TryDelete(panelSetOrder, caseDocument, orderIdParser) == true) { if (this.TryPublish(caseDocument, accessionOrder, panelSetOrder) == true) { if (panelSetOrder.Distribute == true) { foreach (YellowstonePathology.Business.ReportDistribution.Model.TestOrderReportDistribution testOrderReportDistribution in panelSetOrder.TestOrderReportDistributionCollection) { if (testOrderReportDistribution.Distributed == false) { YellowstonePathology.Business.ReportDistribution.Model.DistributionResult distributionResult = this.Distribute(testOrderReportDistribution, accessionOrder); if (distributionResult.IsComplete == true) { testOrderReportDistribution.TimeOfLastDistribution = DateTime.Now; testOrderReportDistribution.ScheduledDistributionTime = null; testOrderReportDistribution.Distributed = true; string testOrderReportDistributionLogId = Guid.NewGuid().ToString(); string objectId = MongoDB.Bson.ObjectId.GenerateNewId().ToString(); YellowstonePathology.Business.ReportDistribution.Model.TestOrderReportDistributionLog testOrderReportDistributionLog = new YellowstonePathology.Business.ReportDistribution.Model.TestOrderReportDistributionLog(testOrderReportDistributionLogId, objectId); testOrderReportDistributionLog.FromTestOrderReportDistribution(testOrderReportDistribution); testOrderReportDistributionLog.TimeDistributed = DateTime.Now; panelSetOrder.TestOrderReportDistributionLogCollection.Add(testOrderReportDistributionLog); this.m_ReportDistributionLogEntryCollection.AddEntry("INFO", "Publish Next", testOrderReportDistribution.DistributionType, panelSetOrder.ReportNo, panelSetOrder.MasterAccessionNo, testOrderReportDistribution.PhysicianName, testOrderReportDistribution.ClientName, "TestOrderReportDistribution Distributed"); } else { testOrderReportDistribution.ScheduledDistributionTime = DateTime.Now.AddMinutes(30); testOrderReportDistribution.Rescheduled = true; testOrderReportDistribution.RescheduledMessage = distributionResult.Message; this.m_ReportDistributionLogEntryCollection.AddEntry("ERROR", "Publish Next", testOrderReportDistribution.DistributionType, panelSetOrder.ReportNo, panelSetOrder.MasterAccessionNo, testOrderReportDistribution.PhysicianName, testOrderReportDistribution.ClientName, distributionResult.Message); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**", System.Windows.Forms.SystemInformation.UserName, distributionResult.Message); System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("10.1.2.111"); Uri uri = new Uri("http://tempuri.org/"); System.Net.ICredentials credentials = System.Net.CredentialCache.DefaultCredentials; System.Net.NetworkCredential credential = credentials.GetCredential(uri, "Basic"); client.Credentials = credential; client.Send(message); } } } } this.HandleNotificationEmail(panelSetOrder); panelSetOrder.Published = true; panelSetOrder.TimeLastPublished = DateTime.Now; panelSetOrder.ScheduledPublishTime = null; Business.Persistence.DocumentGateway.Instance.Save(); } } processCount += 1; if (processCount == maxProcessCount) { break; } } } YellowstonePathology.Business.Persistence.DocumentGateway.Instance.Push(this); }
static void Main(string[] args) { // . as decimal-seperator, etc System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; //TODO: // field xml Output.Info("*****************\n***** START *****\n*****************"); //Output.Info("Using: " + Properties.Settings.Default.output_format + " as output format"); string filter = null; if (args.Count() > 0) { filter = args[0]; Output.Info("Filter op vergelijking: '" + filter + "'"); } #if !DEBUG try { #endif var provider = DbProviderFactories.GetFactory(Properties.Settings.Default.databaseprovider); var connection = provider.CreateConnection(); connection.ConnectionString = Properties.Settings.Default.databaseconnection.Replace("${WORKING_DIRECTORY}", System.IO.Directory.GetCurrentDirectory()); // If error.message == The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. ==> are we debugging in 32-bits (x86) mode? connection.Open(); #region COMPARE var command = provider.CreateCommand(); if (filter == null) { command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "vergelijking WHERE actief = -1 ORDER BY vergelijkingnaam"; } else { command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "vergelijking WHERE vergelijkingnaam LIKE '" + filter + "'"; } command.Connection = connection; var adapter = provider.CreateDataAdapter(); adapter.SelectCommand = command; var table = new DataTable(); adapter.Fill(table); foreach (DataRow comparerow in table.Rows) { var vergelijking = new Vergelijking(Convert.ToString(comparerow["vergelijkingnaam"]), Convert.ToString(comparerow["veldtoewijzing"]), Convert.ToString(comparerow["referentiedatabronnaam"]), Convert.ToString(comparerow["analysedatabronnaam"])); Output.Info("START: " + vergelijking.Naam); #if !DEBUG try { #endif // what shall we do with the console reporter? DatabaseReporter reporter = new DatabaseReporter(provider, connection); XPathDocument document = new XPathDocument(new StringReader(vergelijking.VeldToewijzing)); XPathNavigator compareconfig = document.CreateNavigator(); compareconfig = compareconfig.SelectSingleNode("/compare"); reporter.Start( vergelijking.Naam, vergelijking.ReferentieDatabronNaam, vergelijking.AnalyseDatabronNaam, vergelijking.VeldToewijzing, null, null ); // create the data sources Output.Info("\t[" + vergelijking.ReferentieDatabronNaam + "] data will be loaded"); var reference = Databron.GetData(provider, connection, vergelijking.ReferentieDatabronNaam); vergelijking.Reference = reference; //RegistratieSource reference = new RegistratieSource(referencetable); Output.Info("\t[" + vergelijking.ReferentieDatabronNaam + "] data loaded (#" + reference.Count + ")"); Output.Info("\t[" + vergelijking.AnalyseDatabronNaam + "] data will be loaded"); var analysis = Databron.GetData(provider, connection, vergelijking.AnalyseDatabronNaam); vergelijking.Analysis = analysis; //RegistratieSource analysis = new RegistratieSource(analysetable); Output.Info("\t[" + vergelijking.AnalyseDatabronNaam + "] data loaded (#" + analysis.Count + ")"); // check the columns (better error messages!) #region matching foreach (XPathNavigator field in compareconfig.Select("//field")) { XPathNavigator referencefield = field.SelectSingleNode("@reference-field"); if (referencefield != null && !reference.Columns.Contains(referencefield.Value)) { Output.Warn("reference-column:" + field.SelectSingleNode("@reference-field").Value + " not found in:"); foreach (var name in reference.Columns) { Output.Warn("\t" + name.ToString()); } throw new InvalidDataException("reference-column:" + field.SelectSingleNode("@reference-field").Value + " not found "); } XPathNavigator analysisfield = field.SelectSingleNode("@analysis-field"); if (analysisfield != null && !analysis.Columns.Contains(analysisfield.Value)) { Output.Warn("analysis-column:" + field.SelectSingleNode("@analysis-field").Value + " not found in:"); foreach (var name in analysis.Columns) { Output.Warn("\t" + name.ToString()); } throw new InvalidDataException("analysis-column:" + field.SelectSingleNode("@analysis-field").Value + " not found"); } } Output.Info("\t[check] field references correct"); #endregion // export into csv, so we can use i-spiegel #region export csv /* * { * DirectoryInfo exportdirectory = new DirectoryInfo("data"); * if (!exportdirectory.Exists) exportdirectory.Create(); * exportdirectory = new DirectoryInfo("data\\" + comparename); * if (!exportdirectory.Exists) exportdirectory.Create(); * * List<string> n = new List<string>(); * List<string> r = new List<string>(); * List<string> a = new List<string>(); * foreach (XPathNavigator field in compareconfig.Select("//field")) * { * n.Add(field.SelectSingleNode("@name").Value); * if (field.SelectSingleNode("@reference-field") != null) * { * r.Add(field.SelectSingleNode("@reference-field").Value); * } * else * { * r.Add(null); * } * if (field.SelectSingleNode("@analysis-field") != null) * { * a.Add(field.SelectSingleNode("@analysis-field").Value); * } * else * { * a.Add(null); * } * } * Output.Info("\tSTART: exporting the data"); * try * { * reference.Export(r, n, exportdirectory, compareconfig.SelectSingleNode("@reference").Value); * analysis.Export(a, n, exportdirectory, compareconfig.SelectSingleNode("@analysis").Value); * * Output.Info("\tSTOP: exporting the data"); * } * catch(Exception ex) { * Output.Warn("\tERROR: exporting the data", ex); * } * } */ #endregion // matches #region build matchers Dictionary <string, List <string>[]> matchers = new Dictionary <string, List <string>[]>(); foreach (XPathNavigator match in compareconfig.Select("match")) { String name = match.SelectSingleNode("@id").Value; List <string> r = new List <string>(); List <string> a = new List <string>(); foreach (XPathNavigator field in match.Select("field")) { r.Add(field.SelectSingleNode("@reference-field").Value); a.Add(field.SelectSingleNode("@analysis-field").Value); } List <string>[] ra = new List <string> [2]; ra[0] = r; ra[1] = a; if (matchers.ContainsKey(name)) { throw new Exception("match with id:" + name + " does already exist!"); } matchers.Add(name, ra); } #endregion // create compare array #region build lookup String primary = compareconfig.SelectSingleNode("@primary").Value; SortedDictionary <RegistratieItem, DataRegel> lookup = reference.GetSortedList(matchers[primary][0].ToArray()); Output.Info("\t[lookup] index succesfull"); #endregion // now start the loop foreach (DataRegel regel in analysis.Regels) { // primary match string[] analysisrows = matchers[primary][1].ToArray(); //RegistratieItem matcher = analysis.GetFieldValues(row, analysisrows); RegistratieItem matcher = regel.GetFieldValues(analysisrows); if (!lookup.ContainsKey(matcher)) { //reporter.EntryNotFound(vergelijking, primary, row, matcher); reporter.EntryNotFound(vergelijking, primary, regel, matcher); continue; } // System.Data.DataRow found = lookup[matcher]; DataRegel found = lookup[matcher]; bool fullmatch = true; bool firsterror = true; foreach (string matchername in matchers.Keys) { if (matchername != primary) { string[] analysisfields = matchers[matchername][1].ToArray(); string[] referencefields = matchers[matchername][0].ToArray(); // RegistratieItem a = analysis.GetFieldValues(row, analysisfields); // RegistratieItem r = reference.GetFieldValues(found, referencefields); RegistratieItem a = regel.GetFieldValues(analysisfields); RegistratieItem r = found.GetFieldValues(referencefields); if (!a.Equals(r)) { fullmatch = false; reporter.EntryNoMatch(vergelijking, regel, matcher, found, matchername, a, r, matcher, firsterror); firsterror = false; } } } if (fullmatch) { reporter.EntryMatch(vergelijking, regel, found, matcher); } } reporter.Stop( vergelijking.Naam, reference.ApplicatieNaam, analysis.ApplicatieNaam, reference.ReferentieQuery, analysis.ReferentieQuery, reference.GemeenteCode, analysis.GemeenteCode, analysis.Count, reference.Count); Output.Info("STOP: " + vergelijking.Naam); #if !DEBUG } catch (Exception ex) { Output.Warn("ERROR PROCESSING: " + vergelijking.Naam, ex); } #endif } #endregion COMPARE #region CHECK command = provider.CreateCommand(); // "small detail", in access boolean: true = false and visaversa if (filter == null) { command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "controle WHERE actief = -1 ORDER BY controlenaam"; } else { command.CommandText = "SELECT * FROM " + Properties.Settings.Default.databaseprefix + "controle WHERE controlenaam LIKE '" + filter + "'"; } command.Connection = connection; adapter = provider.CreateDataAdapter(); adapter.SelectCommand = command; table = new DataTable(); adapter.Fill(table); foreach (DataRow checkrow in table.Rows) { string controlenaam = Convert.ToString(checkrow["controlenaam"]); string datasourcename = Convert.ToString(checkrow["databronnaam"]); string primary = Convert.ToString(checkrow["sleutelkolom"]); string columnname = Convert.ToString(checkrow["controlekolom"]); string checkvalue = Convert.ToString(checkrow["controlewaarde"]); var vergelijking = new Vergelijking(controlenaam, primary, datasourcename, columnname); Output.Info("START: " + controlenaam); #if !DEBUG try { #endif DatabaseReporter reporter = new DatabaseReporter(provider, connection); reporter.Start(controlenaam, null, datasourcename, columnname + "='" + checkvalue + "'", null, datasourcename); var controle = Databron.GetData(provider, connection, datasourcename); foreach (DataRegel datarow in controle.Regels) { var found = datarow[columnname]; if (Convert.ToString(found).Equals(checkvalue)) { reporter.EntryMatch(vergelijking, controlenaam, primary, columnname, checkvalue, datarow); } else { reporter.EntryInvalid(vergelijking, controlenaam, primary, columnname, checkvalue, datarow); } } reporter.Stop( controlenaam, controle.ApplicatieNaam, null, controle.ReferentieQuery, null, controle.GemeenteCode, null, controle.Regels.Count, 0); Output.Info("STOP: " + controlenaam); #if !DEBUG } catch (Exception ex) { Output.Warn("ERROR PROCESSING: " + controlenaam, ex); } #endif } #endregion CHECK connection.Close(); Output.Info("*****************\n***** STOP ******\n*****************"); #if !DEBUG } catch (Exception ex) { Output.Error("*****************\n***** ERROR ******\n*****************", ex); } #endif if (Properties.Settings.Default.email_smtp.Length > 0) { System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(Properties.Settings.Default.email_receiver); message.Subject = Properties.Settings.Default.email_subject; message.From = new System.Net.Mail.MailAddress(Properties.Settings.Default.email_from); message.Body = Output.ToString(); System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Properties.Settings.Default.email_smtp); smtp.UseDefaultCredentials = true; smtp.Send(message); } else { Console.WriteLine("\n\n=== no emailserver configured, waiting for user-input ==="); Console.WriteLine("Press Any Key to Continue"); Console.ReadKey(); } }
public static void EnviarCorreoActivarCliente(string email, string fechaIni, string fechaFin, string empresa) { /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); //Direccion de correo electronico a la que queremos enviar el mensaje mmsg.To.Add(email); //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.Subject = "Activación Usuario CabuSoft Inventarios"; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje //mmsg.Bcc.Add("*****@*****.**"); //Opcional //Cuerpo del Mensaje mmsg.Body = "Señores(as) <strong>" + empresa + "</strong> <br/><br/><br/>" + "Su cuenta fue activada exitosamente en nuestro Software de Inventarios<br/>"; mmsg.Body += "Periodo Suscrito: " + fechaIni + " hasta el " + fechaFin; mmsg.Body += "<br/>Usted o su empresa ya puede, a través del siguiente enlace hacer uso de su herramienta archivística: http://xeropapel.com/gestionDocumental/Account/Login.aspx <br/><br/>"; mmsg.Body += "Recuerde ingresar con el usuario y contraseña que usted mismo creó."; mmsg.Body += "<br/><br/><br/>CabuSoft.COM"; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = true; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress(ConfigurationSettings.AppSettings["emailUser"]); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["emailUser"], Utils.Base64Decode(ConfigurationSettings.AppSettings["emailPass"])); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail cliente.Port = Convert.ToInt16(ConfigurationSettings.AppSettings["port"]); cliente.EnableSsl = Convert.ToBoolean(ConfigurationSettings.AppSettings["SSL"]); cliente.Host = ConfigurationSettings.AppSettings["host"]; //Para Gmail "smtp.gmail.com"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); } catch (System.Net.Mail.SmtpException ex) { Console.Write("Error al enviar el correo: " + ex); //Aquí gestionamos los errores al intentar enviar el correo } }
public static bool SendSenha(string nome, string from, string to, string subject, string mensagem) { System.Net.Mail.SmtpClient s = null; try { s = new System.Net.Mail.SmtpClient("smtp.live.com", 587); s.EnableSsl = true; s.UseDefaultCredentials = false; s.Credentials = new System.Net.NetworkCredential("*****@*****.**", "bandtec1234"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage( new System.Net.Mail.MailAddress(from), new System.Net.Mail.MailAddress(to)); message.Body = mensagem; message.BodyEncoding = Encoding.UTF8; message.Subject = subject; message.SubjectEncoding = Encoding.UTF8; s.Send(message); s.Dispose(); return true; } catch { return false; } finally { if (s != null) s.Dispose(); } }