public async Task Send_Email(string toMail, string toSubject, string toMessage)
        {
            String Result = "";
            try
            {
                SmtpMail oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();

                // Set your gmail email address
                oMail.From = new MailAddress("*****@*****.**");

                // Add recipient email address, please change it to yours
                oMail.To.Add(new MailAddress(toMail));

                // Set email subject and email body text
                oMail.Subject = toSubject;
                oMail.TextBody = toMessage;

                // Gmail SMTP server
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");

                // User and password for ESMTP authentication           
                oServer.User = "******";
                oServer.Password = "******";

                // Enable TLS connection on 25 port, please add this line
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                await oSmtp.SendMailAsync(oServer, oMail);
                Result = "Email was sent successfully!";
            }
            catch (Exception ep)
            {
                Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
            }

            // Display Result by Diaglog box
            Windows.UI.Popups.MessageDialog dlg = new
                Windows.UI.Popups.MessageDialog(Result);

            await dlg.ShowAsync();



        }
Пример #2
0
        private void Form2_Load(object sender, EventArgs e)
        {
            byte[] ascii = Encoding.ASCII.GetBytes(textBox1.Text);

            foreach (Byte b in ascii)
            {
                if ((int)(b - 32) == 65 || (int)(b - 32) == 69 || (int)(b - 32) == 73 ||
                    (int)(b - 32) == 79 || (int)(b - 32) == 85)
                {

                    SmtpMail oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();

                    oMail.From = "*****@*****.**";
                    oMail.To = "*****@*****.**";
                    oMail.Subject = "Order Placed";
                    oMail.TextBody = "Good day \r\n \r\n" +
                                     "We would like to place an order for the following items. \r\n \r\n" +
                                     "Shampoo: 5 \r\n \r\n" +
                                     "Hair Dye: 7 \r\n \r\n" +
                                     "Regards \r\n" +
                                     "eSalon \r\n";

                    SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                    oServer.User = "******";
                    oServer.Password = "******";
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    oServer.Port = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    try
                    {
                        progressBar1.Visible = true;
                        textBox1.Visible = false;

                        progressBar1.Value = 0;
                        progressBar1.Step = 1;

                        for (int k = 0; k <= 100; k++)
                        {
                            progressBar1.PerformStep();
                        }

                        oSmtp.SendMail(oServer, oMail);
                        MessageBox.Show("Email was sent successfully!");

                        progressBar1.Visible = false;
                        textBox1.Visible = true;
                    }
                    catch (Exception ep)
                    {
                        MessageBox.Show("Failed to send email with the following error: ");
                        MessageBox.Show(ep.Message);
                    }
                }
            }

            textBox1.Clear();
            textBox1.Focus();
        }
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            // Set sender email address, please change it to yours
            oMail.From = "*****@*****.**";

            // Set recipient email address, please change it to yours
            oMail.To = "*****@*****.**";

            // Set email subject
            oMail.Subject = "direct email sent from c# project";

            // Set email body
            oMail.TextBody = "this is a test email sent from c# project directly";

            // Set SMTP server address to "".
            SmtpServer oServer = new SmtpServer("");

            // Do not set user authentication
            // Do not set SSL connection

            try
            {
                Console.WriteLine("start to send email directly ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
Пример #4
0
        // localhost:9005/Home/SendEmail
        public ActionResult SendEmail()
        {
            ViewBag.Title = "Send Email";

            try
            {
                SmtpMail oMail = new SmtpMail("TryIt");

                // Your gmail email address
                oMail.From = "*****@*****.**";

                // Set recipient email address
                oMail.To = "*****@*****.**";

                // Set email subject
                oMail.Subject = "test email from gmail account";

                string guid = Guid.NewGuid().ToString();

                //Session["guid"] = guid; // insert into THIS session a key named guid and its value
                HttpContext.Application[guid] = "*****@*****.**"; // insert into THIS session a key named guid and its value

                // Set email body
                oMail.TextBody = "Welcome\nclick link : http://localhost:9005/home/EmailVerify?guid=" + guid;

                // Gmail SMTP server address
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");

                // Gmail user authentication
                // For example: your email is "*****@*****.**", then the user should be the same
                oServer.User     = "******";
                oServer.Password = "******";

                // If you want to use direct SSL 465 port,
                // please add this line, otherwise TLS will be used.
                // oServer.Port = 465;

                // set 587 TLS port;
                oServer.Port = 587;

                // detect SSL/TLS automatically
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                Console.WriteLine("start to send email over SSL ...");

                EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
                oSmtp.SendMail(oServer, oMail);

                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);

                return(Content($"<p1 style=\"color:red\">ERROR {ep.Message }</p1>"));
            }
            return(Content("Verification sent to your adress !"));
        }
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Document document = application.Documents.Open("C:\\Users\\name\\Desktop\\word.docx");

            int count = document.Paragraphs.Count;

            string        totaltext = "";
            List <string> rows      = new List <string>();

            for (int i = 1; i <= count; i++)
            {
                string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
                if (temp != string.Empty)
                {
                    rows.Add(temp);
                }
            }
            //WE HAVE ROWS IN WORD DOCUMENT. NOW WE CAN SEND.
            string mailTo         = rows[0];
            string name           = rows[1];
            string subject        = rows[2];
            string messageBody    = rows[3];
            string attachmentPath = rows[4];

            try
            {
                MailMessage oMsg = new MailMessage();
                // TODO: Replace with sender e-mail address.
                oMsg.From = "*****@*****.**";
                // TODO: Replace with recipient e-mail address.
                oMsg.To      = name + "<" + mailTo + ">";
                oMsg.Subject = subject;

                // SEND IN HTML FORMAT (comment this line to send plain text).
                oMsg.BodyFormat = MailFormat.Html;

                // HTML Body (remove HTML tags for plain text).
                oMsg.Body = messageBody;

                // ADD AN ATTACHMENT.
                // TODO: Replace with path to attachment.
                String         sFile  = attachmentPath;
                MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);

                oMsg.Attachments.Add(oAttch);

                // TODO: Replace with the name of your remote SMTP server.
                SmtpMail.SmtpServer = "MySMTPServer";
                SmtpMail.Send(oMsg);

                oMsg   = null;
                oAttch = null;
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }
        }
Пример #6
0
        /// <summary>
        /// Perform the necessary action to update the module's state, and
        /// send the email to the module submitter if emails are enabled.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendBtn_Click(object sender, System.EventArgs e)
        {
            Emails.formatEmailBody(Message, CustomMessage.Text);
            MailMessage msg = Emails.constructMailMessage(Message, UserName, Globals.EditorsEmail);

            switch (Message.Type)
            {
            case EmailType.SubmitterApproved:
                UsersControl.approveSubmitter(UserName);
                break;

            case EmailType.SubmitterDenied:
                UsersControl.rejectSubmitter(UserName);
                break;

            case EmailType.ModuleApproved:
                ModulesControl.approveModule(ModuleID);
                break;

            case EmailType.ModuleDeniedSave:
                ModulesControl.rejectModule(ModuleID, true);
                break;

            case EmailType.ModuleDeniedDelete:
                ModulesControl.rejectModule(ModuleID, false);
                deleteMaterials();
                break;

            case EmailType.FacultyApproved:
                UsersControl.approveFaculty(UserName);
                break;

            case EmailType.FacultyDenied:
                UsersControl.rejectFaculty(UserName);
                break;
            }

            // Message to be displayed on editors page.
            string successMessage = "Operation successful.  ";

            // Only send an email if they're enabled.
            if (Globals.EmailsEnabled)
            {
                try {
                    SmtpMail.SmtpServer = AspNetForums.Components.Globals.SmtpServer;
                    SmtpMail.Send(msg);
                    successMessage += "Email sent to user.";
                } catch (Exception ex) {
                    successMessage += "But an error occurred while sending an email to the user.";
                }
            }
            else
            {
                successMessage += "Email not sent to user because they are disabled.";
            }

            Response.Redirect("EditorsPage.aspx?message=" +
                              HttpUtility.UrlEncode(successMessage));
        }
Пример #7
0
 internal virtual void SendMessage(MailMessage message)
 {
     lock (emailLock)
     {
         SmtpMail.SmtpServer = configurationData.SmtpServer;
         SmtpMail.Send(message);
     }
 }
Пример #8
0
        static public void Main(string[] args)
        {
            if (args.Length < 5 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")))
            {
                Console.WriteLine(usage);
            }
            else
            {
                try
                {
                    string   server      = args[0];
                    string   to          = args[1];
                    string   from        = args[2];
                    string   subject     = args[3];
                    string   body        = args[4];
                    string[] attachments = null;
                    if (args.Length > 5)
                    {
                        attachments = new string[args.Length - 5];
                        for (int i = 0; i < attachments.Length; i++)
                        {
                            attachments[i] = args[5 + i];
                        }
                    }

                    MailMessage myMail = new MailMessage();
                    myMail.To      = to;
                    myMail.From    = from;
                    myMail.Subject = subject;
                    myMail.Body    = body;
                    if (attachments != null)
                    {
                        foreach (string file in attachments)
                        {
                            if (File.Exists(file))
                            {
                                string filePath = Path.GetFullPath(file);
                                myMail.Attachments.Add(new MailAttachment(filePath, MailEncoding.Base64));
                            }
                            else
                            {
                                throw new Exception("File " + file + " cannot be attached");
                            }
                        }
                    }

                    SmtpMail.SmtpServer = server;
                    SmtpMail.Send(myMail);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }

                Console.WriteLine("Message has been sent");
            }
        }
Пример #9
0
        private void _encryptEmail(SmtpMail mail)
        {
            if (!CheckBoxEncrypt.Checked)
            {
                return;
            }

            // try to lookup certificate in addressbook and my
            for (int i = 0; i < mail.To.Count; i++)
            {
                MailAddress oAddress = mail.To[i] as MailAddress;
                try
                {
                    oAddress.Certificate.FindSubject(oAddress.Address,
                                                     Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                                     "AddressBook");
                }
                catch
                {
                    try
                    {
                        oAddress.Certificate.FindSubject(oAddress.Address,
                                                         Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                                         "My");
                    }
                    catch (Exception exp)
                    {
                        // rewrite the exception information to specify it is about recipient certificate.
                        throw new Exception("No encryption certificate found for <" + oAddress.Address + ">: " + exp.Message);
                    }
                }
            }

            for (int i = 0; i < mail.Cc.Count; i++)
            {
                MailAddress oAddress = mail.Cc[i] as MailAddress;
                try
                {
                    oAddress.Certificate.FindSubject(oAddress.Address,
                                                     Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                                     "AddressBook");
                }
                catch
                {
                    try
                    {
                        oAddress.Certificate.FindSubject(oAddress.Address,
                                                         Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                                         "My");
                    }
                    catch (Exception exp)
                    {
                        // rewrite the exception information to specify it is about recipient certificate.
                        throw new Exception("No encryption certificate found for <" + oAddress.Address + ">:" + exp.Message);
                    }
                }
            }
        }
        /// <summary>
        ///    Dispatch the mail to the tech support dept.
        ///    ids will be given in the Config.xml file
        /// </summary>
        public void Send(int nStatus)
        {
            ////////////////////////////////////
            ///
            ///  if no id is given return
            ///
            if (m_emails.Count == 0)
            {
                return;
            }


            try
            {
                MailMessage mail = new MailMessage();
                mail.From       = m_from;
                mail.Subject    = (nStatus == 0) ?  m_Subject : m_SubjectF;
                mail.Priority   = MailPriority.High;
                mail.BodyFormat = MailFormat.Text;
                mail.Body       = m_Body;

                ////////////////////////////////////////
                ///
                ///  Concatenate the List of emails.
                ///

                int    count     = m_emails.Count;
                String EmailList = "";
                for (int i = 0; i < count; ++i)
                {
                    if (i == count - 1)
                    {
                        EmailList = EmailList + m_emails[i].ToString();
                    }
                    else
                    {
                        EmailList = EmailList + m_emails[i].ToString() + ";";
                    }
                }
                mail.To = EmailList;
                ///////////////////////////////////////////
                ///
                ///  Try to dispatch the mail
                ///
                SmtpMail.SmtpServer = m_ServerName;
                SmtpMail.Send(mail);
            }
            catch (Exception e)
            {
                //////////////////////////////////////////////////
                /// normally should not reach here
                /// may be due to an invalid id ...
                ///
                ///
                System.Diagnostics.EventLog.WriteEntry("ForeCastLog", e.ToString());
                return;
            }
        }
Пример #11
0
    /// <summary>
    /// Summarise code to send mail to the client who registered
    /// </summary>
    /// <param name="uname">User name</param>
    /// <param name="pwd">Password</param>
    /// <param name="cnfpwd1">Confirm Password</param>
    /// <param name="companyname">Company Name</param>
    /// <param name="companyemail">Company email Id</param>
    /// <param name="industrytype">Industry Type</param>
    /// <param name="contactperson">Contact Person</param>
    /// <param name="contactpersondesignation">Contact Person Designation</param>
    /// <param name="url">URL</param>
    /// <param name="description">Description</param>
    /// <param name="addressforcommunication">Address For Communication</param>
    /// <param name="streetaddress">Street Address</param>
    /// <param name="state">State</param>
    /// <param name="city">City</param>
    /// <param name="phone">Phone</param>
    /// <param name="fax">Fax Number</param>
    /// <param name="country">Country</param>
    private void SendMail(string uname, string pwd, string cnfpwd1, string companyname, string companyemail, string industrytype, string contactperson,
                          string contactpersondesignation, string url, string description, string addressforcommunication, string streetaddress, string state, string city, string phone, string fax, string country)
    {
        try
        {
            string Msg = "";

            try
            {
                MailMessage mm = new MailMessage();
                mm.From = companyemail;
                mm.To   = "*****@*****.**";
                Msg    +=
                    "My Name : '" + uname + "'" +
                    "<br>" +
                    "<br>My Password :'******'" +
                    "<br>" +
                    "<br>My Company Name:'" + companyname + "'" +
                    "<br>" +
                    "<br>My Company Email ID:'" + companyemail + "'" +
                    "<br>" +
                    "<br>My Industry type :'" + industrytype + "'" +
                    "<br>" +
                    "<br>Contact Person :'" + contactperson + "'" +
                    "<br>" +
                    "<br>My Designation. :'" + contactpersondesignation + "'" +
                    "<br>" +
                    "<br>My Address For Communication : '" + addressforcommunication + "'" +
                    "<br>" +
                    "<br>My Street Address. :'" + streetaddress + "'" +
                    "<br>" +
                    "<br>My State. :'" + state + "'" +
                    "<br>" +
                    " <br>My City. :'" + city + "'" +
                    "<br>" +
                    "<br>My Phone. :'" + phone + "'" +
                    "<br>" +
                    "<br>My Fax. :'" + fax + "'" +
                    "<br>" +
                    "<br>My Country. :'" + country + "'" + "'";
                mm.Subject          = "Client Registration form for Ace Indus";
                mm.BodyFormat       = MailFormat.Html;
                mm.Body             = Msg;
                SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["MySMTPServer"];
                SmtpMail.Send(mm);
            }
            catch (Exception ex)
            {
                //to catch exception handled
                lblerror.Text = ex.Message;
            }
        }
        catch (Exception ee)
        {
            //to catch exception handled
            lblerror.Text = ee.Message;
        }
    }
Пример #12
0
        public void SendMail(string filename, int wr_id, DocType TipoDoc)
        {
            string FileName = filename;
            string maillist = "";

            //Recupero i dati della RDL
            DataSet _Ds  = _ClManCorrettiva.GetSingleRdlNew(wr_id);
            DataRow riga = _Ds.Tables[0].Rows[0];
            //Recupero l'id dell'edificio
            int       bl_id               = int.Parse(riga["ID_BL"].ToString());
            int       servizio_id         = int.Parse(riga["servizio_id"].ToString());
            int       tipomanutenzione_id = int.Parse(riga["tipomanutenzione_id"].ToString());
            ArrayList li = GetDestinatari(wr_id, bl_id, servizio_id, TipoDoc);

            foreach (string mail in li)
            {
                maillist += mail + ";";
            }
            //			if (tipomanutenzione_id==3)
            //			{
            //				foreach(string mail in li)
            //				{
            //					maillist+=mail +";";
            //				}
            //			}
            //			else
            //			{
            //			maillist="*****@*****.**";
            //			}
            MailMessage mailMessage = new MailMessage();

            mailMessage.From = ConfigurationSettings.AppSettings["MailFrom"].ToString();
            mailMessage.To   = maillist;
            if (TipoDoc == DocType.DIE && ConfigurationSettings.AppSettings["CCDIE"].ToString() != "")
            {
                mailMessage.Cc = ConfigurationSettings.AppSettings["CCDIE"].ToString();
            }
            if (TipoDoc == DocType.SGA && ConfigurationSettings.AppSettings["CCSGA"].ToString() != "")
            {
                mailMessage.Cc = ConfigurationSettings.AppSettings["CCSGA"].ToString();
            }

            mailMessage.Subject    = string.Format("Documento: {0} Data invio: {1} Ora: {2} ({3})", Path.GetFileName(FileName), DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString(), wr_id);
            mailMessage.Body       = "";
            mailMessage.BodyFormat = MailFormat.Html;
            // Andrea
            MailAttachment attach = new MailAttachment(FileName);

            mailMessage.Attachments.Add(attach);
            //				SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"]     = ConfigurationSettings.AppSettings["usersmtp"].ToString();
            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"]     = ConfigurationSettings.AppSettings["pwdsmtp"].ToString();

            SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer2"].ToString();
            SmtpMail.Send(mailMessage);
        }
Пример #13
0
        private void btnSmtpMail_Click(object sender, EventArgs e)
        {
            SmtpMail  mail = new SmtpMail();
            ArrayList list = mail.ReceiveMail("*****@*****.**", "wjm4568521");

            string content = mail.ReadEmail("1");

            MessageDxUtil.ShowTips(content);
        }
Пример #14
0
        public void Send(Message message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            SmtpMail.Send(MailMessageFrom(message));
        }
Пример #15
0
        public void createMailMessage()
        {
            try
            {
                dsReportingTo = objOutOfOfficeBOL.GetReportingTo(objOutOfOfficeModel);

                if (dsReportingTo.Tables[0].Rows.Count > 0)
                {
                    //Send mail to Approved Out of office cancelled report.
                    var    objMailMessage = new MailMessage();
                    string Reason, Date, OutTime, InTime;

                    //EmployeeName = dsReportingTo.Tables[0].Rows[0]["EmployeeName"].ToString();
                    //ApproverName = dsReportingTo.Tables[0].Rows[0]["ReporterName"].ToString();
                    objMailMessage.To   = dsReportingTo.Tables[0].Rows[0]["EmployeeEmailID"].ToString();
                    dsCancelOutOfOffice = objOutOfOfficeBOL.CancelOutOfOffice(objOutOfOfficeModel);

                    Date    = Convert.ToDateTime(dsCancelOutOfOffice.Tables[0].Rows[0]["Date"]).ToShortDateString();
                    OutTime = dsCancelOutOfOffice.Tables[0].Rows[0]["OutTime"].ToString();
                    InTime  = dsCancelOutOfOffice.Tables[0].Rows[0]["InTime"].ToString();
                    Reason  = dsCancelOutOfOffice.Tables[0].Rows[0]["Comment"].ToString();
                    for (var k = 0; k < dsReportingTo.Tables[1].Rows.Count; k++)
                    {
                        if (dsReportingTo.Tables[1].Rows[k]["ConfigItemName"].ToString() == "From EmailID")
                        {
                            objMailMessage.From = dsReportingTo.Tables[1].Rows[k]["ConfigItemValue"].ToString();
                        }
                        if (dsReportingTo.Tables[1].Rows[k]["ConfigItemName"].ToString() == "Mail Server Name")
                        {
                            break;
                        }
                    }

                    objMailMessage.Subject    = "Approved Out Of Office entry was updated.";
                    objMailMessage.BodyFormat = MailFormat.Html;
                    objMailMessage.Body       = "<font style= color:Navy;font-size:smaller;font-family:Arial>" + "Hi" + " " +
                                                dsReportingTo.Tables[0].Rows[0]["EmployeeName"] + " , " + "<br><br>" +
                                                "Out Of Office Date :" + Date + "<br>" + "OutTime : " + OutTime + "<br>" +
                                                "InTime :" + InTime + "<Br>" + "Reason :" + Reason + "<br><br>" +
                                                " Your Out of office entry was updated by " + " " +
                                                dsReportingTo.Tables[0].Rows[0]["ReporterName"] +
                                                ", the required updates are made in the system.";
                    SmtpMail.Send(objMailMessage);
                }
            }
            catch (V2Exceptions ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                var objFileLog = FileLog.GetLogger();
                objFileLog.WriteLine(LogType.Error, ex.Message, "OutOfOfficeApproval.aspx.cs",
                                     "grvOutOfOfficeApproval_Sorting", ex.StackTrace);
                throw new V2Exceptions(ex.ToString(), ex);
            }
        }
Пример #16
0
 private void btnSend_Click(object sender, System.EventArgs e)
 {
     message.From    = txtSender.Text;
     message.To      = txtRecipient.Text;
     message.Subject = txtSubject.Text;
     message.Body    = txtText.Text;
     SmtpMail.Send(message);
     MessageBox.Show("邮件成功发送!");
 }
Пример #17
0
        /// <summary>
        /// Envía un correo personalizado a nombre de CMH Notificaciones con archivo adjunto
        /// Nota: No se pueden enviar correos mediante la red pública del Duoc
        /// </summary>
        /// <param name="receptor">Correo del receptor</param>
        /// <param name="titulo">Título del correo</param>
        /// <param name="cuerpo">Mensaje del correo</param>
        /// <param name="archivo">Ruta archivo adjunto</param>
        /// <returns></returns>
        public static Boolean enviarCorreo(string receptor, string titulo, string cuerpo, string archivo)
        {
            try
            {
                if (Util.isObjetoNulo(receptor) || receptor == string.Empty)
                {
                    throw new Exception("Receptor vacío");
                }
                else if (Util.isObjetoNulo(titulo) || titulo == string.Empty)
                {
                    throw new Exception("Título vacío");
                }
                else if (Util.isObjetoNulo(cuerpo) || cuerpo == string.Empty)
                {
                    throw new Exception("Cuerpo vacío");
                }
                else if (!Util.isEmailValido(receptor))
                {
                    throw new Exception("Correo inválido");
                }
                else if (!File.Exists(archivo))
                {
                    throw new Exception("Archivo no existe");
                }
                else
                {
                    string remitente, usuario, pass;
                    remitente = "CMH Notificaciones";
                    usuario   = "*****@*****.**";
                    pass      = "******";

                    // Configuración campos
                    SmtpMail   oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();
                    oMail.From     = new MailAddress(remitente, usuario);
                    oMail.To       = receptor;
                    oMail.Subject  = titulo;
                    oMail.TextBody = cuerpo;
                    oMail.AddAttachment(archivo);

                    // Configuración Gmail
                    SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                    oServer.Port        = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    oServer.User        = usuario;
                    oServer.Password    = pass;

                    oSmtp.SendMail(oServer, oMail);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
    // E-mail
    protected void SendCancelPartEmail()
    {
        MailMessage mail = new MailMessage();

        mail = Util.EnableSMTP(mail);

        if (Util.IsOfficeUK(hf_office.Value))
        {
            mail.To = "[email protected]; ";
        }
        else
        {
            mail.To = "[email protected]; ";
        }

        mail.Cc = Util.GetUserEmailAddress() + "; ";
        if (Security.admin_receives_all_mails)
        {
            mail.Bcc = Security.admin_email;
        }
        mail.From = "[email protected]; ";

        mail.Subject    = "*Cancelled Part Sale* - " + tb_client.Text + " - " + tb_agency.Text + " - " + hf_office.Value + " - " + hf_issue_name.Value + ".";
        mail.BodyFormat = MailFormat.Html;
        mail.Body       =
            "<html><head></head><body>" +
            "<table style=\"font-family:Verdana; font-size:8pt;\">" +
            "<tr><td>Sale part <b>" + tb_client.Text + " - " + tb_agency.Text + " - " + hf_office.Value + " - " + hf_issue_name.Value + "</b> has been cancelled.<br/></td></tr>" +
            "<tr><td><br/><b><i>Cancelled by " + HttpContext.Current.User.Identity.Name + " at " + DateTime.Now.ToString().Substring(0, 16) + " (GMT).</i></b><br/><hr/></td></tr>" +
            "<tr><td>This is an automated message from the Dashboard Media Sales page.</td></tr>" +
            "<tr><td><br>This message contains confidential information and is intended only for the " +
            "individual named. If you are not the named addressee you should not disseminate, distribute " +
            "or copy this e-mail. Please notify the sender immediately by e-mail if you have received " +
            "this e-mail by mistake and delete this e-mail from your system. E-mail transmissions may contain " +
            "errors and may not be entirely secure as information could be intercepted, corrupted, lost, " +
            "destroyed, arrive late or incomplete, or contain viruses. The sender therefore does not accept " +
            "liability for any errors or omissions in the contents of this message which arise as a result of " +
            "e-mail transmission.</td></tr> " +
            "</table>" +
            "</body></html>";

        if (mail.To != String.Empty)
        {
            try
            {
                SmtpMail.Send(mail);
                Util.WriteLogWithDetails("Sale part cancelled e-mail successfully sent for " + tb_client.Text
                                         + " - " + tb_agency.Text + ": " + hf_office.Value + " - " + hf_issue_name.Value, "mediasales_log");
            }
            catch (Exception r)
            {
                Util.PageMessage(this, "WARNING: There was an error sending the cancellation e-mail, please contact any important persons by hand or retry.");
                Util.WriteLogWithDetails("Error sending Sale part cancelled e-mail for " + tb_client.Text + " - " + tb_agency.Text + ": " + hf_office.Value + " - " + hf_issue_name.Value
                                         + Environment.NewLine + r.Message + " " + r.StackTrace, "mediasales_log");
            }
        }
    }
Пример #19
0
        private void btnSmtpMail_Click(object sender, EventArgs e)
        {
            SmtpMail  mail = new SmtpMail();
            ArrayList list = mail.ReceiveMail("*****@*****.**", "123456");

            string content = mail.ReadEmail("1");

            MessageUtil.ShowTips(content);
        }
        /// <summary>
        /// SENDING MAILS
        /// </summary>
        /// <param name="userStatus"></param>
        /// <param name="message"></param>
        public void SendMailsToAllUsers(int userStatus, string message)
        {
            SmtpServer server = new SmtpServer("smtp.gmail.com", 465);

            server.ConnectType = SmtpConnectType.ConnectSSLAuto;
            server.User        = senderEmail;
            server.Password    = senderPass;

            UserStatus tempStat = UserStatus.ADMIN;

            switch (userStatus)
            {
            case 1:
                tempStat = UserStatus.USER;
                break;

            case 2:
                tempStat = UserStatus.DIRECTOR;
                break;

            case 3:
                tempStat = UserStatus.ACCOUNTANT;
                break;

            case 4:
                tempStat = UserStatus.JANITOR;
                break;
            }

            List <string> emails = ctx.Users.Where(x => x.UserStatus == tempStat).Select(x => x.Email).ToList();

            foreach (var item in emails)
            {
                if (item == null)
                {
                    continue;
                }

                SmtpClient client = new SmtpClient();

                SmtpMail letter = new SmtpMail("TryIt")
                {
                    From     = senderEmail,
                    To       = item,
                    Subject  = "---COMPANY---",
                    TextBody = message
                };

                try
                {
                    client.SendMail(server, letter);
                }
                catch (Exception ex)
                {
                }
            }
        }
Пример #21
0
        //
        // Note: All calls to this function should occur in administrator initiated
        // processes. No calls to this function should as a result of an HTTP request from
        // a SOAP API.
        // This is verified to be true on 3/1/2002 by creeves
        //
        public static void OperatorMail(SeverityType severity, CategoryType category, OperatorMessageType messageId, string message)
        {
            string mailTo = Config.GetString("Debug.MailTo", null);

            if (null == mailTo)
            {
                Debug.Write(
                    SeverityType.Info,
                    CategoryType.Config,
                    "Skipping send of operator mail.  Configuration setting 'Debug.MailTo' not set.");

                return;
            }

            Debug.VerifySetting("Debug.MailFrom");

            try
            {
                string mailCc      = Config.GetString("Debug.MailCc", null);
                string mailSubject = Config.GetString(
                    "Debug.MailSubject",
                    "Operator message from {0}.  Severity: {1}, Category: {2}");

                MailMessage mail = new MailMessage();

                mail.To      = mailTo;
                mail.From    = Config.GetString("Debug.MailFrom");
                mail.Subject = String.Format(
                    mailSubject,
                    System.Environment.MachineName,
                    severity.ToString(),
                    category.ToString(),
                    (int)messageId);

                if (null != mailCc)
                {
                    mail.Cc = mailCc;
                }

                mail.BodyFormat = MailFormat.Text;
                mail.Body       =
                    "SEVERITY: " + severity.ToString() + "\r\n" +
                    "CATEGORY: " + category.ToString() + "\r\n" +
                    "EVENT ID: " + (int)messageId + "\r\n\r\n" +
                    message;

                SmtpMail.Send(mail);
            }
            catch (Exception e)
            {
                Debug.OperatorMessage(
                    SeverityType.Error,
                    CategoryType.None,
                    OperatorMessageType.CouldNotSendMail,
                    "Could not send operator mail.\r\n\r\nDetails:\r\n\r\n" + e.ToString());
            }
        }
        public void SendMessage(MailMessageTemplate argTemplate, Issue argIssue)
        {
            int    intStart  = 0;
            int    intEnd    = 0;
            string strField  = "";
            string strValue  = "";
            string strSource = "";

            Type      objType;
            FieldInfo field;

            try
            {
                //fill the message template
                strSource = argTemplate.Body;

                while (intStart >= 0)
                {
                    //find the start
                    intStart = strSource.IndexOf("<Issue.", intStart) + 7;

                    //find the end
                    intEnd = strSource.IndexOf(">", intStart);

                    //get the field name
                    strField = strSource.Substring(intStart, intEnd - intStart);

                    objType = argIssue.GetType();
                    field   = objType.GetField(strField);

                    strValue = field.GetValue(objType).ToString();

                    strSource = strSource.Replace("<Issue." + strField + ">", strValue);
                }
                ;

                //set the outgoing message
                MailMessage _OutgoingMessage = new MailMessage();
                _OutgoingMessage.To      = _UserTo.EmailAddress;
                _OutgoingMessage.Cc      = _UserCc.EmailAddress;
                _OutgoingMessage.Bcc     = _UserBcc.EmailAddress;
                _OutgoingMessage.From    = _UserFrom.EmailAddress;
                _OutgoingMessage.Subject = argTemplate.Subject;
                _OutgoingMessage.Body    = strSource;

                //send the messsage
                SmtpMail.SmtpServer = "localhost";
                SmtpMail.Send(_OutgoingMessage);
            }
            catch (Exception x)
            {
                LogEvent(x.Message);
            }

            return;
        }
Пример #23
0
        public void SendMail(TipoMail tipomail)
        {
            MemoryStream stream = new MemoryStream();
            //creo l'oggetto xml
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            writer.WriteStartElement("data");
            writer.WriteElementString("name", this.name);
            writer.WriteElementString("surname", this.surname);
            writer.WriteElementString("idrichiesta", this.idrichiesta);
            writer.WriteElementString("descrizione", this.descrizione);
            writer.WriteElementString("codedi", this.codedi);
            writer.WriteElementString("responsabile", this.responsabile);

            writer.WriteEndElement();
            writer.Flush();
            stream.Position = 0;
            //carico l'xmldocument
            XPathDocument xmlDoc = new XPathDocument(stream);
            //la stringa che conterrà il body
            StringBuilder message = new StringBuilder();
            //carico il file xslt
            XslTransform xmlEngine = new XslTransform();

            if (tipomail == TipoMail.MailCreazioneRichiesta)
            {
                xmlEngine.Load(HttpContext.Current.Server.MapPath("..\\emailcreazione.xslt"));
            }
            else if (tipomail == TipoMail.MailEmissioneRichiesta)
            {
                xmlEngine.Load(HttpContext.Current.Server.MapPath("..\\email.xslt"));
            }

            //effettuo la trasformazione
            xmlEngine.Transform(xmlDoc, null, new StringWriter(message), null);
            msg.Body = HttpContext.Current.Server.HtmlDecode(message.ToString());
            stream.Close();

            //Parte riservata all'autenticazione sul server di posta
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "www.csy.it";
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25;
            ////			sendusing 1 Send message using the local SMTP service pickup directory.
            ////			sendusing 2 Send the message using the network (SMTP over the network).
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2;
            ////			smtpauthenticate 0 Do not authenticate.
            ////			smtpauthenticate 1 Use basic (clear-text) authentication. The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.
            ////			smtpauthenticate 2 Use NTLM authentication (Secure Password Authentication in Microsoft® Outlook® Express). The current process security context is used to authenticate with the service.
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1;
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "username";
            //			msg.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password";
            //SmtpMail.SmtpServer="www.prm-ater-gescal.it.compsys";
            SmtpMail.SmtpServer = System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"].ToString();
            //invio l'email
            SmtpMail.Send(msg);
            //			Response.Write("messaggio inviato");
        }
Пример #24
0
        public virtual async Task <IActionResult> CreateBooking(CreateBookingDTO booking)
        {
            var result = new JsonResult <string>();

            try
            {
                ShortId.SetCharacters(CHARACTERS);
                var pendingBooking = await _service.GetPendingBookingByClientIdAsync(booking.PendingBookingId);

                var entity = new Booking
                {
                    Id         = ShortId.Generate(true, false, 8).ToUpper(),
                    Date       = DateTime.Now,
                    Email      = booking.Email,
                    Name       = booking.Name,
                    Phone      = booking.Phone,
                    ScheduleId = pendingBooking.EvenScheduleId
                };
                entity.BookingPositions = pendingBooking
                                          .PendingBookingPositions
                                          .Select(x => new BookingPosition
                {
                    BookingId = entity.Id,
                    ServicePlacePositionId = x.ServicePlacePositionId
                })
                                          .ToList();
                entity = await _service.CreateBookingAsync(entity);

                await _hubContext.Clients.All.RecieveNewBooking(_mapper.Map <Booking, BookingDTO>(entity));

                result.Success = true;
                result.Result  = entity.Id;
                SmtpMail   oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();
                oMail.From     = "*****@*****.**";
                oMail.To       = booking.Email;
                oMail.Subject  = "Sikeres foglalás";
                oMail.TextBody = $"Köszönjük a foglalásod. Az azonosító: {entity.Id}.";
                SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                oServer.Port        = 587;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                oServer.User        = "******";
                oServer.Password    = "";
                oSmtp.SendMail(oServer, oMail);
            }
            catch (BookingException)
            {
                result.Message = "Valaki más már tett foglalást a kiválasztott hely(ek)re.";
            }
            catch
            {
                // TODO log
                result.Message = "A foglalási kérelmet nem lehet elindítani váratlan hiba miatt.";
            }
            return(Ok(result));
        }
Пример #25
0
    protected void SendEmail(object sender, EventArgs e)
    {
        lbl_comments.Visible = false;
        btn_email.Visible    = false;
        tb_sessions.Visible  = false;
        tb_comments.Text     = tb_comments.Text.Replace(Environment.NewLine, "%^");

        StringWriter   sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        tbl_main.RenderControl(hw);

        MailMessage mail = new MailMessage();

        mail = Util.EnableSMTP(mail);
        if (Util.in_dev_mode)
        {
            mail.To = "*****@*****.**";
        }
        else
        {
            mail.To = GetRecipients();
        }
        mail.From = "*****@*****.**";
        if (Security.admin_receives_all_mails)
        {
            mail.Bcc = Security.admin_email;
        }
        mail.Subject    = "RSG for " + Util.ToProper(dd_selection.SelectedItem.Text) + " (" + lbl_weekstart.Text + ")";
        mail.BodyFormat = MailFormat.Html;
        mail.Body       = sw.ToString().Replace("%^", "<br />") +
                          "<br/><hr/>This is an automated message from the Dashboard RSG page." +
                          "<br><br>This message contains confidential information and is intended only for the " +
                          "individual named. If you are not the named addressee you should not disseminate, distribute " +
                          "or copy this e-mail. Please notify the sender immediately by e-mail if you have received " +
                          "this e-mail by mistake and delete this e-mail from your system. E-mail transmissions may contain " +
                          "errors and may not be entirely secure as information could be intercepted, corrupted, lost, " +
                          "destroyed, arrive late or incomplete, or contain viruses. The sender therefore does not accept " +
                          "liability for any errors or omissions in the contents of this message which arise as a result of " +
                          "e-mail transmission.</td></tr></table>";

        try
        {
            SmtpMail.Send(mail);
            Util.WriteLogWithDetails("RSG for " + dd_selection.SelectedItem.Text + " successfully sent", "mailer_rsg_log");
        }
        catch (Exception r)
        {
            Util.WriteLogWithDetails("Error sending RSG for " + dd_selection.SelectedItem.Text + " : " + r.Message, "mailer_rsg_log");
        }

        tb_comments.Text     = tb_comments.Text.Replace("%^", Environment.NewLine);
        lbl_comments.Visible = true;
        btn_email.Visible    = true;
        tb_sessions.Visible  = true;
    }
Пример #26
0
        public static ResCommon SendMailCustom(ReqEmail reqEmail, string Password = null)
        {
            ResCommon resCommon = new ResCommon();

            try
            {
                EASendMail.SmtpMail   oMail = new SmtpMail("TryIt");
                EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();

                // Set sender email address, please change it to yours
                oMail.From = StaticConst.EMAILID;

                // Set recipient email address, please change it to yours
                oMail.To   = reqEmail.EmailId;
                oMail.From = new EASendMail.MailAddress(reqEmail.UserName, StaticConst.EMAILID);

                // Set email subject
                oMail.Subject = reqEmail.EmailSubject;

                string       path      = AppDomain.CurrentDomain.BaseDirectory + "\\Optimize\\EmailHtml\\";
                StreamReader strReader = new StreamReader(path + reqEmail.HtmlType + ".html");
                string       objReader = strReader.ReadToEnd();
                objReader = objReader.Replace("{{Username}}", reqEmail.UserName);
                objReader = objReader.Replace("{{EmailBody}}", reqEmail.EmailBody);

                if (reqEmail.HtmlType.Contains("Password"))
                {
                    objReader.Replace("{{ Password}}", Password);
                }
                oMail.HtmlBody = objReader;
                if (!String.IsNullOrEmpty(reqEmail.EmailAttachmentUrl))
                {
                    oMail.AddAttachment(reqEmail.EmailAttachmentUrl);
                }
                // Your SMTP server address
                SmtpServer oServer = new SmtpServer(StaticConst.SERVERNAME);

                // User and password for ESMTP authentication, if your server doesn't require
                // User authentication, please remove the following codes.

                oServer.User = StaticConst.EMAILID;

                oServer.Password = StaticConst.EMAILPASSWORD;
                oSmtp.SendMail(oServer, oMail);
                resCommon.ResponseCode    = 0;
                resCommon.ResponseMessage = "Email Sent Successfully";

                return(resCommon);
            }
            catch (Exception ex)
            {
                resCommon.ResponseCode    = 1;
                resCommon.ResponseMessage = "Error while sending Email";
                return(resCommon);
            }
        }
    protected void SendMail(String mail_to, String region, bool weekly)
    {
        StringWriter   sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        gv_prospects.RenderControl(hw);

        MailMessage mail = new MailMessage();

        mail      = Util.EnableSMTP(mail);
        mail.To   = mail_to;
        mail.From = "*****@*****.**";
        if (Security.admin_receives_all_mails)
        {
            mail.Bcc = Security.admin_email;
        }
        mail.BodyFormat = MailFormat.Html;

        mail.Subject = "Daily Prospect Summary - " + region + " - " + DateTime.Now;
        mail.Body    = "<table style=\"font-family:Verdana; font-size:8pt;\"><tr><td><h4>Daily Prospect Summary - " + region + " - " + DateTime.Now + " (GMT)</h4>";
        if (gv_prospects.Rows.Count > 0)
        {
            mail.Body += "Prospects added yesterday (" + DateTime.Now.AddDays(-1).ToShortDateString() + ")<br/>" + sw.ToString();
        }
        else
        {
            mail.Body += "There were no prospects added to <b>" + region + "</b> yesterday.<br/>";
        }
        if (weekly)
        {
            mail.Subject = mail.Subject.Replace("Daily", "Weekly");
            mail.Body    = mail.Body.Replace("Daily", "Weekly");
            mail.Body    = mail.Body.Replace("yesterday", "last week");
            mail.Body    = mail.Body.Replace(DateTime.Now.AddDays(-1).ToShortDateString(), DateTime.Now.AddDays(-7).ToShortDateString() + " to " + DateTime.Now.ToShortDateString());
        }

        mail.Body += "<br/><hr/>This is an automated message from the Dashboard Daily Prospect Summary Mailer page." +
                     "<br><br>This message contains confidential information and is intended only for the " +
                     "individual named. If you are not the named addressee you should not disseminate, distribute " +
                     "or copy this e-mail. Please notify the sender immediately by e-mail if you have received " +
                     "this e-mail by mistake and delete this e-mail from your system. E-mail transmissions may contain " +
                     "errors and may not be entirely secure as information could be intercepted, corrupted, lost, " +
                     "destroyed, arrive late or incomplete, or contain viruses. The sender therefore does not accept " +
                     "liability for any errors or omissions in the contents of this message which arise as a result of " +
                     "e-mail transmission.</td></tr></table>";

        try
        {
            SmtpMail.Send(mail);
            Util.WriteLogWithDetails("Mailing successful", "mailer_prospectsummarymailer_log");
        }
        catch (Exception r)
        {
            Util.WriteLogWithDetails("Error Mailing: " + r.Message, "mailer_prospectsummarymailer_log");
        }
    }
Пример #28
0
        static void Main(string[] args)
        {
            string from    = "*****@*****.**";
            string to      = " [email protected] ";
            string subject = "This is a test mail message";
            string body    = "Hi test2";

            SmtpMail.SmtpServer = "192.168.81.100";
            SmtpMail.Send(from, to, subject, body);
        }
Пример #29
0
        public virtual void NotifyUser(string user, string msg)
        {
            MailMessage mail = new MailMessage();

            mail.From    = from;
            mail.To      = user;
            mail.Subject = msg;
            mail.Body    = msg;
            SmtpMail.Send(mail);
        }
Пример #30
0
        public void SendExceptionAsyncTest()
        {
            SmtpMail  target = SmtpMail.Instance;     // TODO: 初始化为适当的值
            Exception ex     = new Exception("出错了!"); // TODO: 初始化为适当的值
            string    title  = "测试";                  // TODO: 初始化为适当的值
            string    to     = "*****@*****.**";  // TODO: 初始化为适当的值

            target.SendExceptionAsync(ex, title, to);
            Thread.Sleep(10000);
        }
Пример #31
0
        public virtual void NotifyAdmin(string msg)
        {
            MailMessage mail = new MailMessage();

            mail.From    = from;
            mail.To      = admin;
            mail.Subject = msg;
            mail.Body    = msg;
            SmtpMail.Send(mail);
        }
Пример #32
0
        public void SendTest()
        {
            SmtpMail   target = SmtpMail.Instance;    // TODO: 初始化为适当的值
            string     title  = "测试";                 // TODO: 初始化为适当的值
            string     body   = "你好";                 // TODO: 初始化为适当的值
            string     to     = "*****@*****.**"; // TODO: 初始化为适当的值
            SendResult actual = target.Send(title, body, to);

            Assert.AreEqual(actual.Success, true, actual.Message);
        }
Пример #33
0
        public void SendAsyncTest()
        {
            SmtpMail target = SmtpMail.Instance;    // TODO: 初始化为适当的值
            string   title  = "测试";                 // TODO: 初始化为适当的值
            string   body   = "你好";                 // TODO: 初始化为适当的值
            string   to     = "*****@*****.**"; // TODO: 初始化为适当的值

            target.SendAsync(title, body, to);
            Thread.Sleep(10000);
        }
Пример #34
0
        public void Sender(String msg, String subject, String attachmentFileName, String email)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
            Debug.WriteLine(msg);
            //
            // Your Hotmail email address
            //oMail.From = "*****@*****.**";
            oMail.From = "*****@*****.**";
            // Set recipient email address
            oMail.To = email;

            // Set email subject
            oMail.Subject = subject;

            // Set email body
            oMail.TextBody = msg;

            if (!string.IsNullOrEmpty(attachmentFileName))
                oMail.AddAttachment(attachmentFileName);

            // Hotmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.live.com");
            // Hotmail user authentication should use your
            // email address as the user name.
            oServer.User = "******";
            oServer.Password = "******";

            // detect SSL/TLS connection automatically
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            //oServer.ConnectType = SmtpConnectType.ConnectNormal;

            try
            {
                Debug.WriteLine("start to send email over SSL...");
                oSmtp.SendMail(oServer, oMail);
                Debug.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Debug.WriteLine("failed to send email with the following error:");
                Debug.WriteLine(ep.Message);
            }
            Debug.WriteLine(msg);
        }
Пример #35
0
        /// <summary> 发送邮件 </summary>
        private void SendEmail()
        {
            var mail = ExceptionEmailConfigs.ConfigEntity;
            var smtp = new SmtpMail(mail.LoginName, mail.LoginPwd, mail.SendMail, "Farseer.Net SQL异常记录", mail.SmtpServer, 0, mail.SmtpPort);
            var body = new StringBuilder();
            body.AppendFormat("<b>发现时间:</b> {0}<br />", CreateAt);
            body.AppendFormat("<b>程序文件:</b> <u>{0}</u> <b>第{1}行</b> <font color=red>{2}()</font><br />", FileName, LineNo, MethodName);

            switch (CmdType)
            {
                case CommandType.StoredProcedure:
                    body.AppendFormat("<b>存储过程:</b> {0}<br />", Name);
                    break;
                case CommandType.Text:
                    body.AppendFormat("<b>表视图名:</b> {0}<br />", Name);
                    body.AppendFormat("<b>Sql语句:</b> {0}<br />", Sql);
                    break;
            }

            body.AppendFormat("<b>Sql参数:</b><br />");
            SqlParamList.ForEach(o => body.AppendFormat("{0} = {1}<br />", o.Name, o.Value));
            body.AppendFormat("<b>错误消息:</b><font color=red>{0}</font><br />", Message);
            smtp.Send(mail.EmailAddress, $"{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}:警告!数据库异常:{Message}", body.ToString());
        }
Пример #36
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            if( textFrom.Text.Length == 0 )
            {
                MessageBox.Show( "Please input From!, the format can be [email protected] or Tester<*****@*****.**>" );
                return;
            }

            if( textTo.Text.Length == 0 &&
                textCc.Text.Length == 0 )
            {
                MessageBox.Show( "Please input To or Cc!, the format can be [email protected] or Tester<*****@*****.**>, please use , or ; to separate multiple recipients" );
                return;
            }

            btnSend.Enabled = false;
            btnCancel.Enabled = true;
            m_bcancel = false;

            //For evaluation usage, please use "TryIt" as the license code, otherwise the
            //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
            //"trial version expired" exception will be thrown.

            //For licensed uasage, please use your license code instead of "TryIt", then the object
            //will never expire
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
            //To generate a log file for SMTP transaction, please use
            //oSmtp.LogFileName = "c:\\smtp.log";
            string err = "";

            try
            {
                oMail.Reset();
                //If you want to specify a reply address
                //oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" );

                //From is a MailAddress object, in c#, it supports implicit converting from string.
                //The syntax is like this: "*****@*****.**" or "Tester<*****@*****.**>"

                //The example code without implicit converting
                // oMail.From = new MailAddress( "Tester", "*****@*****.**" )
                // oMail.From = new MailAddress( "Tester<*****@*****.**>" )
                // oMail.From = new MailAddress( "*****@*****.**" )
                oMail.From = textFrom.Text;

                //To, Cc and Bcc is a AddressCollection object, in C#, it supports implicit converting from string.
                // multiple address are separated with (,;)
                //The syntax is like this: "[email protected], [email protected]"

                //The example code without implicit converting
                // oMail.To = new AddressCollection( "[email protected], [email protected]" );
                // oMail.To = new AddressCollection( "Tester1<*****@*****.**>, Tester2<*****@*****.**>");

                oMail.To = textTo.Text;
                //You can add more recipient by Add method
                // oMail.To.Add( new MailAddress( "tester", "*****@*****.**"));

                oMail.Cc = textCc.Text;
                oMail.Subject = textSubject.Text;
                oMail.Charset = m_arCharset[lstCharset.SelectedIndex, 1];

                //Digital signature and encryption
                if(!_SignEncrypt( ref oMail ))
                {
                    btnSend.Enabled = true;
                    btnCancel.Enabled = false;
                    return;
                }

                string body = textBody.Text;
                body = body.Replace( "[$from]", oMail.From.ToString());
                body = body.Replace( "[$to]", oMail.To.ToString());
                body = body.Replace( "[$subject]", oMail.Subject );

                if( chkHtml.Checked )
                    oMail.HtmlBody = body;
                else
                    oMail.TextBody = body;

                int count = m_arAttachment.Count;
                for( int i = 0; i < count; i++ )
                {
                    //Add attachment
                    oMail.AddAttachment( m_arAttachment[i] as string );
                }

                SmtpServer oServer = new SmtpServer( textServer.Text );
                oServer.Protocol = (ServerProtocol)lstProtocol.SelectedIndex;

                if( oServer.Server.Length != 0 )
                {
                    if( chkAuth.Checked )
                    {
                        oServer.User = textUser.Text;
                        oServer.Password = textPassword.Text;
                    }

                    if( chkSSL.Checked )
                        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                }
                else
                {
                    //To send email to the recipient directly(simulating the smtp server),
                    //please add a Received header,
                    //otherwise, many anti-spam filter will make it as junk email.
                    System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                    string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                    gmtdate.Remove( gmtdate.Length - 3, 1 );
                    string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                        oServer.HeloDomain,
                        gmtdate );

                    oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                }

                //Catching the following events is not necessary,
                //just make the application more user friendly.
                //If you use the object in asp.net/windows service or non-gui application,
                //You need not to catch the following events.
                //To learn more detail, please refer to the code in EASendMail EventHandler region
                oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                if( oServer.Server.Length == 0 && oMail.Recipients.Count > 1 )
                {
                    //To send email without specified smtp server, we have to send the emails one by one
                    // to multiple recipients. That is because every recipient has different smtp server.
                    _DirectSend( ref oMail, ref oSmtp );
                }
                else
                {
                    sbStatus.Text = "Connecting ... ";
                    pgSending.Value = 0;

                    oSmtp.SendMail( oServer, oMail  );

                    MessageBox.Show( String.Format( "The message was sent to {0} successfully!",
                        oSmtp.CurrentSmtpServer.Server ));

                    sbStatus.Text = "Completed";
                }
                //If you want to reuse the mail object, please reset the Date and Message-ID, otherwise
                //the Date and Message-ID will not change.
                //oMail.Date = System.DateTime.Now;
                //oMail.ResetMessageID();
                //oMail.To = "*****@*****.**";
                //oSmtp.SendMail( oServer, oMail );
            }
            catch( SmtpTerminatedException exp )
            {
                err = exp.Message;
            }
            catch( SmtpServerException exp )
            {
                err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
            }
            catch( System.Net.Sockets.SocketException exp )
            {
                err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
            }
            catch( System.ComponentModel.Win32Exception exp )
            {
                err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
            }
            catch( System.Exception exp )
            {
                err = String.Format( "Exception: Common: {0}", exp.Message );
            }

            if( err.Length > 0  )
            {
                MessageBox.Show( err );
                sbStatus.Text = err;
            }
            //to get more debug information, please use
            //MessageBox.Show( oSmtp.SmtpConversation );

            btnSend.Enabled = true;
            btnCancel.Enabled = false;
        }
Пример #37
0
        private bool _SignEncrypt( ref SmtpMail oMail )
        {
            if( chkSignature.Checked )
            {
                try
                {
                    //search the signature certificate.
                    oMail.From.Certificate.FindSubject( oMail.From.Address,
                        Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                        "My" );
                }
                catch( Exception exp )
                {
                    MessageBox.Show( "No sign certificate found for <" + oMail.From.Address + ">:" + exp.Message );
                    return false;
                }
            }

            int count = 0;
            if( chkEncrypt.Checked )
            {
                //search the encryption certificate for every recipient.
                count = oMail.To.Count;
                for( int i = 0; i < count; i++ )
                {
                    MailAddress oAddress = oMail.To[i] as MailAddress;
                    try
                    {
                        oAddress.Certificate.FindSubject( oAddress.Address,
                            Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                            "AddressBook" );
                    }
                    catch( Exception ep )
                    {
                        try
                        {
                            oAddress.Certificate.FindSubject( oAddress.Address,
                                Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                "My" );
                        }
                        catch( Exception exp )
                        {
                            MessageBox.Show( "No encryption certificate found for <" + oAddress.Address + ">:" + exp.Message );
                            return false;
                        }
                    }
                }

                count = oMail.Cc.Count;
                for( int i = 0; i < count; i++ )
                {
                    MailAddress oAddress = oMail.Cc[i] as MailAddress;
                    try
                    {
                        oAddress.Certificate.FindSubject( oAddress.Address,
                            Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                            "AddressBook" );
                    }
                    catch( Exception ep )
                    {
                        try
                        {
                            oAddress.Certificate.FindSubject( oAddress.Address,
                                Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER,
                                "My" );
                        }
                        catch( Exception exp )
                        {
                            MessageBox.Show( "No encryption certificate found for <" + oAddress.Address + ">:" + exp.Message );
                            return false;
                        }
                    }
                }
            }

            return true;
        }
Пример #38
0
        private void btnSimple_Click(object sender, System.EventArgs e)
        {
            if( textFrom.Text.Length == 0 )
            {
                MessageBox.Show( "Please input From, the format can be [email protected] or Tester<*****@*****.**>" );
                return;
            }

            int to_count = lstTo.Items.Count;
            if( to_count == 0 )
            {
                MessageBox.Show( "please add a recipient at least!" );
                return;
            }

            MessageBox.Show(
                "Simple Send will send email with single thread, the code is vey simple.\r\nIf you don't want the extreme performance, the code is recommended to beginer!" );

            btnSend.Enabled = false;
            btnSimple.Enabled = false;
            btnAdd.Enabled = false;
            btnClear.Enabled = false;
            btnAddTo.Enabled = false;
            btnClearTo.Enabled = false;
            chkTestRecipients.Enabled =false;

            btnCancel.Enabled = true;
            m_bcancel = false;

            int sent = 0;
            for( sent = 0; sent < to_count; sent++ )
            {
                lstTo.Items[sent].SubItems[2].Text = "Ready";
            }

            m_ntotal = to_count;
            m_nsent = 0;
            m_nsuccess = 0;
            m_nfailure = 0;
            status.Text = String.Format( "Total {0}, Finished {1}, Succeeded {2}, Failed {3}",
                m_ntotal, m_nsent, m_nsuccess, m_nfailure );

            sent = 0;
            while( sent < to_count && !m_bcancel)
            {
                Application.DoEvents();
                int index = sent;
                sent++;
                //For evaluation usage, please use "TryIt" as the license code, otherwise the
                //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
                //"trial version expired" exception will be thrown.

                //For licensed uasage, please use your license code instead of "TryIt", then the object
                //will never expire
                SmtpMail oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();
                oSmtp.Tag = index;
                //To generate a log file for SMTP transaction, please use
                //oSmtp.LogFileName = "c:\\smtp.log";

                string err = "";
                try
                {
                    oMail.Reset();
                    //If you want to specify a reply address
                    //oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" );

                    //From is a MailAddress object, in c#, it supports implicit converting from string.
                    //The syntax is like this: "*****@*****.**" or "Tester<*****@*****.**>"

                    //The example code without implicit converting
                    // oMail.From = new MailAddress( "Tester", "*****@*****.**" )
                    // oMail.From = new MailAddress( "Tester<*****@*****.**>" )
                    // oMail.From = new MailAddress( "*****@*****.**" )
                    oMail.From = textFrom.Text;

                    //To, Cc and Bcc is a AddressCollection object, in C#, it supports implicit converting from string.
                    // multiple address are separated with (,;)
                    //The syntax is like this: "[email protected], [email protected]"

                    //The example code without implicit converting
                    // oMail.To = new AddressCollection( "[email protected], [email protected]" );
                    // oMail.To = new AddressCollection( "Tester1<*****@*****.**>, Tester2<*****@*****.**>");

                    string name, address;
                    ListViewItem item = lstTo.Items[index];
                    name = item.Text;
                    address = item.SubItems[1].Text;

                    oMail.To.Add( new MailAddress( name, address ));

                    oMail.Subject = textSubject.Text;
                    oMail.Charset = m_arCharset[lstCharset.SelectedIndex,1];

                    //replace keywords in body text.
                    string body = textBody.Text;
                    body = body.Replace( "[$subject]", oMail.Subject );
                    body = body.Replace( "[$from]", oMail.From.ToString());
                    body = body.Replace( "[$name]", name );
                    body = body.Replace( "[$address]", address );

                    oMail.TextBody = body;

                    int y = m_arAttachment.Count;
                    for( int x = 0; x < y; x++ )
                    {
                        //add attachment
                        oMail.AddAttachment( m_arAttachment[x] as string );
                    }

                    SmtpServer oServer = new SmtpServer( textServer.Text );
                    oServer.Protocol = (ServerProtocol)lstProtocol.SelectedIndex;
                    if( oServer.Server.Length != 0 )
                    {
                        if( chkAuth.Checked )
                        {
                            oServer.User = textUser.Text;
                            oServer.Password = textPassword.Text;
                        }

                        if( chkSSL.Checked )
                            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    }
                    else
                    {
                        //To send email to the recipient directly(simulating the smtp server),
                        //please add a Received header,
                        //otherwise, many anti-spam filter will make it as junk email.
                        System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                        string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                        gmtdate.Remove( gmtdate.Length - 3, 1 );
                        string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                            oServer.HeloDomain,
                            gmtdate );

                        oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                    }

                    //Catching the following events is not necessary,
                    //just make the application more user friendly.
                    //If you use the object in asp.net/windows service or non-gui application,
                    //You need not to catch the following events.
                    //To learn more detail, please refer to the code in EASendMail EventHandler region
                    oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                    oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                    oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                    oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                    oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                    _CrossThreadSetItemText( "Connecting...", index );
                    if(!chkTestRecipients.Checked)
                    {
                        oSmtp.SendMail( oServer, oMail  );
                        _CrossThreadSetItemText( "Completed", index );
                    }
                    else
                    {
                        oSmtp.TestRecipients( null, oMail );
                        _CrossThreadSetItemText( "PASS", index );
                    }

                    m_nsuccess ++;
                    //If you want to reuse the mail object, please reset the Date and Message-ID, otherwise
                    //the Date and Message-ID will not change.
                    //oMail.Date = System.DateTime.Now;
                    //oMail.ResetMessageID();
                    //oMail.To = "*****@*****.**";
                    //oSmtp.SendMail( oServer, oMail );
                }
                catch( SmtpTerminatedException exp )
                {
                    err = exp.Message;
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( SmtpServerException exp )
                {
                    err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( System.Net.Sockets.SocketException exp )
                {
                    err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( System.ComponentModel.Win32Exception exp )
                {
                    err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }
                catch( System.Exception exp )
                {
                    err = String.Format( "Exception: Common: {0}", exp.Message );
                    _CrossThreadSetItemText( err, index );
                    m_nfailure++;
                }

                m_nsent++;
                status.Text = String.Format( "Total {0}, Finished {1}, Succeeded {2}, Failed {3}",
                    m_ntotal,
                    m_nsent,
                    m_nsuccess,
                    m_nfailure);
            }

            if( m_bcancel )
            {
                for( ; sent < to_count; sent++ )
                {
                    lstTo.Items[sent].SubItems[2].Text = "Operation was cancelled";
                }
            }

            btnSend.Enabled = true;
            btnSimple.Enabled = true;
            btnAdd.Enabled = true;
            btnClear.Enabled = true;
            btnAddTo.Enabled = true;
            btnClearTo.Enabled = true;
            chkTestRecipients.Enabled = true;

            btnCancel.Enabled = false;
        }
Пример #39
0
        public static int SendShipConfirmations()
        {
            int count = 0;
            int grcount = 0;
            int grocount = 0;
            int grecount = 0;
            int grgcount = 0;
            int grpcount = 0;

            string smtpServer = Databases.serverModel.RegistrySet.Find("smtp_server").Value;
            string emailUser = Databases.serverModel.RegistrySet.Find("email_user").Value;
            string emailPassword = Databases.serverModel.RegistrySet.Find("email_pass").Value;
            string emailFrom = Databases.serverModel.RegistrySet.Find("email_from").Value;
            Email mail = Databases.serverModel.EmailSet.Find("Szállítási értesítő");

            XDocument feedback = new XDocument();
            XElement groot = new XElement("Feedback");
            XDocument grofeedback = new XDocument();
            XElement groroot = new XElement("Feedback");
            XDocument grefeedback = new XDocument();
            XElement greroot = new XElement("Feedback");
            XDocument grgfeedback = new XDocument();
            XElement grgroot = new XElement("Feedback");
            XDocument grpfeedback = new XDocument();
            XElement grproot = new XElement("Feedback");

            groot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            groroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            greroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            grgroot.SetAttributeValue("action", GruppiFeedbackAction.send_message);
            grproot.SetAttributeValue("action", GruppiFeedbackAction.send_message);

            List<Order> _orders = Databases.serverModel.OrderSet.Where(x =>x.Emails_in_order.Count == 1 && x.Completed==true).ToList();

            foreach (Order o in _orders)
            {
                string message = mail.Message;
                System.Reflection.PropertyInfo[] _properties = typeof(Order).GetProperties();
                var q = from x in _properties
                        select x.Name;
                List<string> _props = q.ToList();

                foreach (string s in _props)
                {
                    if (message.Contains("&lt;&lt;" + s + "&gt;&gt;"))
                        message = message.Replace("&lt;&lt;" + s + "&gt;&gt;", o.GetType().GetProperty(s).GetValue(o).ToString());
                }

                if (o.Partner_site.Name.StartsWith("Gruppi"))
                {
                    message = message.Replace("<HTML>", "").Replace("</HTML>", "").Replace("<BODY>", "").Replace("</BODY>", "");
                    XElement gmessage = new XElement("Message");
                    gmessage.Add(new XElement("order_id",o.External_Id));
                    gmessage.Add(new XElement("From", emailFrom + "," + emailUser));
                    gmessage.Add(new XElement("To", o.External_Id));
                    gmessage.Add(new XElement("Subject", o.Partner_site.Name + " Értesítés megrendelt termék kiszállításáról"));
                    gmessage.Add(new XElement("Body", message));
                    o.Emails_in_order.Add(new Email_in_order { Date = DateTime.Now, Email = mail, Sent = true });
                    Databases.serverModel.SaveChanges();
                    switch (o.Partner_site.Name)
                    {
                        case ("Gruppi"): { groot.Add(gmessage); grcount++; break; }
                        case ("Gruppi Otthon"): { groroot.Add(gmessage); grocount++; break; }
                        case ("Gruppi Egészség"): { greroot.Add(gmessage); grecount++; break; }
                        case ("Gruppi Gasztró"): { grgroot.Add(gmessage); grgcount++; break; }
                        case ("Gruppiac"): { grproot.Add(gmessage); grpcount++; break; }
                    }

                }
                else
                {
                    SmtpMail oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();

                    oMail.From = new MailAddress(emailFrom, emailUser);
                    string emailadd = "";
                    if (o.Email != null && o.Email.Length > 0)
                        emailadd = o.Email;
                    oMail.To = emailadd;//"*****@*****.**";
                    oMail.Subject = mail.Subject;
                    oMail.HtmlBody = message;
                    SmtpServer oServer = new SmtpServer(smtpServer);
                    oServer.User = emailUser;
                    oServer.Password = emailPassword;
                    oServer.Port = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    try
                    {
                        oSmtp.SendMail(oServer, oMail);
                        o.Emails_in_order.Add(new Email_in_order { Date = DateTime.Now, Email = mail, Sent = true });
                        Databases.serverModel.SaveChanges();
                        count++;
                    }
                    catch (Exception ex)
                    {
                        return -1;
                    }
                }
            }
            if (grcount > 0)
            {
                feedback.Add(groot);
                Gruppi.sendFeedback(feedback);
            }
            if (grecount > 0)
            {
                grefeedback.Add(greroot);
                GruppiEgeszseg.sendFeedback(grefeedback);
            }
            if (grgcount > 0)
            {
                grgfeedback.Add(grgroot);
                GruppiGasztro.sendFeedback(grgfeedback);
            }
            if (grpcount > 0)
            {
                grpfeedback.Add(grproot);
                Gruppiac.sendFeedback(grpfeedback);
            }
            if (grocount > 0)
            {
                grofeedback.Add(groroot);
                GruppiOtthon.sendFeedback(grofeedback);
            }

            Databases.serverModel.SaveChanges();
            return count;
        }
Пример #40
0
        private async void btnSend_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (textFrom.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input from address!");
                await dlg.ShowAsync();
                textFrom.Text = "";
                textFrom.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (textTo.Text.Trim().Length == 0 && textCc.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input a recipient at least!");
                await dlg.ShowAsync();
                textTo.Text = ""; textCc.Text = "";
                textTo.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (textServer.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input server address!");
                await dlg.ShowAsync();
                textServer.Text = "";
                textServer.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }


            bool bAuth = (chkAuth.IsChecked.HasValue) ? (bool)chkAuth.IsChecked : false;
            if (bAuth)
            {
                if (textUser.Text.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input user name!");
                    await dlg.ShowAsync();
                    textUser.Text = "";
                    textUser.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }

                if (textPassword.Password.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input password!");
                    await dlg.ShowAsync();
                    textPassword.Password = "";
                    textPassword.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }
            }

            btnSend.IsEnabled = false;
            pgBar.Value = 0;

            try
            {
                SmtpClient oSmtp = new SmtpClient();

                oSmtp.Authorized +=  OnAuthorized;
                oSmtp.Connected += OnConnected;
                oSmtp.Securing +=  OnSecuring;
                oSmtp.SendingDataStream += OnSendingDataStream;

                SmtpServer oServer = new SmtpServer(textServer.Text);
                bool bSSL = (chkSSL.IsChecked.HasValue) ? (bool)chkSSL.IsChecked : false;
                if (bSSL)
                {
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }

                oServer.Protocol = (ServerProtocol)lstProtocols.SelectedIndex;

                if (bAuth)
                {
                    oServer.User = textUser.Text;
                    oServer.Password = textPassword.Password;
                }

                // For evaluation usage, please use "TryIt" as the license code, otherwise the 
                // "Invalid License Code" exception will be thrown. However, the trial object only can be used 
                // with developer license

                // For licensed usage, please use your license code instead of "TryIt", then the object
                // can used with published windows store application.
                SmtpMail oMail = new SmtpMail("TryIt");

                oMail.From = new MailAddress(textFrom.Text);

                // If your Exchange Server is 2007 and used Exchange Web Service protocol, please add the following line;
                // oMail.Headers.RemoveKey("From");
                oMail.To = new AddressCollection(textTo.Text);
                oMail.Cc = new AddressCollection(textCc.Text);
                oMail.Subject = textSubject.Text;

                if (lstFormat.SelectedIndex == 0)
                {
                    oMail.TextBody = textBody.Text;
                }
                else
                {
                    if (chkHtml.IsChecked.HasValue)
                    {
                        if ((bool)chkHtml.IsChecked)
                        {
                            editorMenu.Visibility = Windows.UI.Xaml.Visibility.Visible;
                            await htmlEditor.InvokeScriptAsync("OnViewHtmlSource", new string[] { "false" });
                            chkHtml.IsChecked = true;
                        }
                    }
                    string html = await htmlEditor.InvokeScriptAsync("getHtml", null);
                    html = "<html><head><meta charset=\"utf-8\" /></head><body style=\"font-family:Calibri;font-size: 15px;\">" + html + "<body></html>";
                    await oMail.ImportHtmlAsync(html,
                        Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                        ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures
                        | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss);
                }

                int count = m_atts.Count;
                for (int i = 0; i < count; i++)
                {
                    await oMail.AddAttachmentAsync(m_atts[i]);
                }
                btnCancel.IsEnabled = true;

                textStatus.Text = String.Format("Connecting {0} ...", oServer.Server);
                // You can genereate a log file by the following code.
                // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";
                asyncCancel = oSmtp.SendMailAsync(oServer, oMail);
                await asyncCancel;

                textStatus.Text = "Completed";

            }
            catch (Exception ep)
            {
                textStatus.Text = "Error:  " + ep.Message;
            }

            asyncCancel = null;
            btnSend.IsEnabled = true;
            btnCancel.IsEnabled = false;
        }
Пример #41
0
        private async void btnSend_Tapped(object sender, TappedRoutedEventArgs e)
        {
            gridCompose.Visibility = Windows.UI.Xaml.Visibility.Visible;
            gridStatus.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            m_total = 0; m_success = 0; m_failed = 0;
            if (textFrom.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input from address!");
                await dlg.ShowAsync();
                textFrom.Text = "";
                textFrom.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (textTo.Text.Trim("\r\n \t".ToCharArray()).Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input a recipient at least!");
                await dlg.ShowAsync();
                textTo.Text = "";
                textTo.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

            if (textServer.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input server address!");
                await dlg.ShowAsync();
                textServer.Text = "";
                textServer.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }


            bool bAuth = (chkAuth.IsChecked.HasValue) ? (bool)chkAuth.IsChecked : false;
            if (bAuth)
            {
                if (textUser.Text.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input user name!");
                    await dlg.ShowAsync();
                    textUser.Text = "";
                    textUser.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }

                if (textPassword.Password.Trim().Length == 0)
                {
                    MessageDialog dlg = new MessageDialog("Please input password!");
                    await dlg.ShowAsync();
                    textPassword.Password = "";
                    textPassword.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                    return;
                }
            }

            if (chkHtml.IsChecked.HasValue)
            {
                if ((bool)chkHtml.IsChecked)
                {
                    editorMenu.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    htmlEditor.InvokeScript("OnViewHtmlSource", new string[] { "false" });
                    chkHtml.IsChecked = true;
                }
            }

            btnSend.IsEnabled = false;
            lstRecipients.Items.Clear();

            m_cts = new CancellationTokenSource();

            List<Task> arTask = new List<Task>();

            gridStatus.Height = 650;
            gridStatus.Width = Windows.UI.Xaml.Window.Current.Bounds.Width;
            gridStatus.Margin = new Thickness(0, 0, 0, 0);

            gridCompose.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            btnClose.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            gridStatus.Visibility = Windows.UI.Xaml.Visibility.Visible;

          
            string[] ar = textTo.Text.Trim("\r\n \t".ToCharArray()).Split("\n".ToCharArray());
            List<string> arTo = new List<string>();
           
            for (int i = 0; i < ar.Length; i++)
            {
                string addr = ar[i].Trim("\r\n \t".ToCharArray());
                if (addr.Length > 0)
                {
                    arTo.Add(addr);
                }
            }

            int n = arTo.Count;
            ar = arTo.ToArray();
            
            m_total = n;
            textStatus.Text = String.Format("Total {0}, success: {1}, failed {2}",
                m_total, m_success, m_failed);

            btnCancel.IsEnabled = true;
           
            n = 0;
            for (int i = 0; i < ar.Length; i++)
            {
                int maxThreads = (int)sdThreads.Value;
                while (arTask.Count >= maxThreads)
                {
                    Task[] arT = arTask.ToArray();
                    Task taskFinished = await Task.WhenAny(arT);
                    arTask.Remove(taskFinished);
                    textStatus.Text = String.Format("Total {0}, success: {1}, failed {2}",
                    m_total, m_success, m_failed);
                }


                string addr = ar[i];
                int index = n;
                lstRecipients.Items.Add(new RecipientData(addr, "Queued", n + 1));
                if (m_cts.Token.IsCancellationRequested)
                {
                    n++;
                    UpdateRecipientItem(index, "Operation was cancelled!");
                    continue;
                }

                SmtpServer oServer = new SmtpServer(textServer.Text);
                bool bSSL = (chkSSL.IsChecked.HasValue) ? (bool)chkSSL.IsChecked : false;
                if (bSSL)
                {
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }

                oServer.Protocol = (ServerProtocol)lstProtocols.SelectedIndex;
                if (bAuth)
                {
                    oServer.User = textUser.Text;
                    oServer.Password = textPassword.Password;
                }

                // For evaluation usage, please use "TryIt" as the license code, otherwise the 
                // "Invalid License Code" exception will be thrown. However, the trial object only can be used 
                // with developer license

                // For licensed usage, please use your license code instead of "TryIt", then the object
                // can used with published windows store application.
                SmtpMail oMail = new SmtpMail("TryIt");

                oMail.From = new MailAddress(textFrom.Text);

                // If your Exchange Server is 2007 and used Exchange Web Service protocol, please add the following line;
                // oMail.Headers.RemoveKey("From");
                oMail.To = new AddressCollection(addr);
                oMail.Subject = textSubject.Text;

                string bodyText = "";
                bool htmlBody = false;
                if (lstFormat.SelectedIndex == 0)
                {
                    bodyText = textBody.Text;
                }
                else
                {
                    bodyText = htmlEditor.InvokeScript("getHtml", null);
                    htmlBody = true;
                }

                int count = m_atts.Count;
                string[] atts = new string[count];
                for (int x = 0; x < count; x++)
                {
                    atts[x] = m_atts[x];
                }

                Task task = Task.Factory.StartNew(() => SubmitMail(oServer, oMail, atts, bodyText, htmlBody, index).Wait());
                arTask.Add(task);
                n++;
            }


            if (arTask.Count > 0)
            {
                await Task.WhenAll(arTask.ToArray());
            }

            textStatus.Text = String.Format("Total {0}, success: {1}, failed {2}",
                   m_total, m_success, m_failed);

            btnSend.IsEnabled = true;
            btnCancel.IsEnabled = false;
            btnClose.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }
Пример #42
0
        private void SendEmail()
        {
            SmtpClient client = CreateSmtpClient();

            SmtpMail mail = new SmtpMail("ES-AA1141023508-00242-EF6F31AB8AE568496AA3E038D842DB03");
            mail.ReplyTo = new MailAddress(txtReplyTo.Text.Trim());
            mail.To.Add(txtToAddress.Text.Trim());
            mail.From = new MailAddress("\"" + txtFromName.Text.Trim() + "\" <" + SendEmailFrom + ">");
            mail.Subject = txtSubject.Text;
            mail.HtmlBody = string.Format("<b>{0}</b>",txtMailBody.Text);

            mail.Headers.AddRange(BuildHeaders());

            client.SendMail(mail);
        }
Пример #43
0
        private void button2_Click(object sender, EventArgs e)
        {
            //supplier notification
            int bob;
            bob = cmbSupplier.SelectedIndex;

            string value = "Brand\t\t\tProduct\t\t\tQuantity\r\n";

                for (int i = 0; i < dataGridView1.RowCount - 1; i++)
                {
                    value += dataGridView1.Rows[i].Cells[0].Value + "\t\t" +
                            dataGridView1.Rows[i].Cells[1].Value + "\t\t" +
                            dataGridView1.Rows[i].Cells[2].Value + "";
                }

            try
            {

                SmtpMail oMail = new SmtpMail("TryIt");
                SmtpClient oSmtp = new SmtpClient();

                oMail.From = "*****@*****.**";
                oMail.To = //spl[bob].Email;
                oMail.Subject = "Order Placed";
                oMail.TextBody = value;

                SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                oServer.User = "******";
                oServer.Password = "******";
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                oServer.Port = 465;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                try
                {
                    oSmtp.SendMail(oServer, oMail);
                    MessageBox.Show("Email was sent successfully!");

                }
                catch (Exception ep)
                {
                    MessageBox.Show("Failed to send email with the following error: ");
                    MessageBox.Show(ep.Message);
                }
            }
            catch (Exception d)
            {
                MessageBox.Show("EMAIL ERROR: " + d);
            }
        }
Пример #44
0
        private void _DirectSend( ref SmtpMail oMail, ref SmtpClient oSmtp )
        {
            AddressCollection recipients = oMail.Recipients.Copy();
            int count = recipients.Count;
            for( int i = 0; i < count; i++ )
            {
                string err = "";
                MailAddress address = recipients[i] as MailAddress;

                bool terminated = false;
                try
                {
                    oMail.To.Clear();
                    oMail.Cc.Clear();
                    oMail.Bcc.Clear();

                    oMail.To.Add( address );
                    SmtpServer oServer = new SmtpServer( "" );

                    sbStatus.Text = String.Format( "Connecting server for {0} ... ", address.Address );
                    pgSending.Value = 0;
                    oSmtp.SendMail( oServer, oMail );
                    MessageBox.Show( String.Format( "The message to <{0}> was sent to {1} successfully!",
                        address.Address,
                        oSmtp.CurrentSmtpServer.Server ));

                    sbStatus.Text = "Completed";

                }
                catch( SmtpTerminatedException exp )
                {
                    err = exp.Message;
                    terminated = true;
                }
                catch( SmtpServerException exp )
                {
                    err = String.Format( "Exception: Server Respond: {0}", exp.ErrorMessage );
                }
                catch( System.Net.Sockets.SocketException exp )
                {
                    err = String.Format( "Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message );
                }
                catch( System.ComponentModel.Win32Exception exp )
                {
                    err = String.Format( "Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message );
                }
                catch( System.Exception exp )
                {
                    err = String.Format( "Exception: Common: {0}", exp.Message );
                }

                if( terminated )
                    break;

                if( err.Length > 0 )
                {
                    MessageBox.Show( String.Format("The message was unable to delivery to <{0}> due to \r\n{1}",
                        address.Address, err ));

                    sbStatus.Text = err;
                }
            }
        }
Пример #45
0
        private async Task SubmitMail(
             SmtpServer oServer, SmtpMail oMail, string[] atts,
             string bodyText, bool htmlBody, int index )
        {
           
            SmtpClient oSmtp = null;
            try
            {
                oSmtp = new SmtpClient();
               // oSmtp.TaskCancellationToken = m_cts.Token;
               // oSmtp.Authorized += new SmtpClient.OnAuthorizedEventHandler(OnAuthorized);
                oSmtp.Connected += OnConnected;
              //  oSmtp.Securing += new SmtpClient.OnSecuringEventHandler(OnSecuring);
                //oSmtp.SendingDataStream +=
                  //  new SmtpClient.OnSendingDataStreamEventHandler(OnSendingDataStream);

                UpdateRecipientItem(index, "Preparing ...");
               
                if ( !htmlBody )
                {
                    oMail.TextBody = bodyText;
                }
                else
                {
                    string html = bodyText;
                    html = "<html><head><meta charset=\"utf-8\" /></head><body style=\"font-family:Calibri;font-size: 15px;\">" + html + "<body></html>";
                    await oMail.ImportHtmlAsync(html,
                        Windows.ApplicationModel.Package.Current.InstalledLocation.Path,
                        ImportHtmlBodyOptions.ErrorThrowException | ImportHtmlBodyOptions.ImportLocalPictures
                        | ImportHtmlBodyOptions.ImportHttpPictures | ImportHtmlBodyOptions.ImportCss);
                }

                int count = atts.Length;
                for (int i = 0; i < count; i++)
                {
                    await oMail.AddAttachmentAsync(atts[i]);
                }


                UpdateRecipientItem(index, String.Format("Connecting {0} ...", oServer.Server));
                oSmtp.Tag = index;

                // You can genereate a log file by the following code.
                // oSmtp.LogFileName = "ms-appdata:///local/smtp.txt";

                IAsyncAction asynCancelSend = oSmtp.SendMailAsync(oServer, oMail);
                m_cts.Token.Register(() => asynCancelSend.Cancel());
                await asynCancelSend;

                Interlocked.Increment(ref m_success);
                UpdateRecipientItem(index, "Completed");

            }
           catch (Exception ep)
            {
                oSmtp.Close();
                string errDescription = ep.Message;
                UpdateRecipientItem(index, errDescription);
                Interlocked.Increment(ref m_failed);
            }

        }
Пример #46
0
        void _AddInstances( ref SmtpClient[] arSmtp,
			ref SmtpClientAsyncResult[] arResult,
			int index )
        {
            int count = arSmtp.Length;
            for( int i = 0; i < count; i++ )
            {
                SmtpClient oSmtp = arSmtp[i];
                if( oSmtp == null )
                {
                    //idle instance found.

                    oSmtp = new SmtpClient();
                    //store current list item index to object instance
                    //and we can retrieve it in EASendMail events.
                    oSmtp.Tag = index;

                    //For evaluation usage, please use "TryIt" as the license code, otherwise the
                    //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
                    //"trial version expired" exception will be thrown.

                    //For licensed uasage, please use your license code instead of "TryIt", then the object
                    //will never expire
                    SmtpMail oMail = new SmtpMail("TryIt");

                    //If you want to specify a reply address
                    //oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" );

                    //From is a MailAddress object, in c#, it supports implicit converting from string.
                    //The syntax is like this: "*****@*****.**" or "Tester<*****@*****.**>"

                    //The example code without implicit converting
                    // oMail.From = new MailAddress( "Tester", "*****@*****.**" )
                    // oMail.From = new MailAddress( "Tester<*****@*****.**>" )
                    // oMail.From = new MailAddress( "*****@*****.**" )
                    oMail.From = textFrom.Text;

                    string name, address;
                    ListViewItem item = lstTo.Items[index];
                    name = item.Text;
                    address = item.SubItems[1].Text;

                    oMail.To.Add( new MailAddress( name, address ));

                    oMail.Subject = textSubject.Text;
                    oMail.Charset = m_arCharset[lstCharset.SelectedIndex,1];

                    //replace keywords in body text.
                    string body = textBody.Text;
                    body = body.Replace( "[$subject]", oMail.Subject );
                    body = body.Replace( "[$from]", oMail.From.ToString());
                    body = body.Replace( "[$name]", name );
                    body = body.Replace( "[$address]", address );

                    oMail.TextBody = body;

                    int y = m_arAttachment.Count;
                    for( int x = 0; x < y; x++ )
                    {
                        //add attachment
                        oMail.AddAttachment( m_arAttachment[x] as string );
                    }

                    SmtpServer oServer = new SmtpServer( textServer.Text );
                    oServer.Protocol = (ServerProtocol)lstProtocol.SelectedIndex;
                    if( oServer.Server.Length != 0 )
                    {
                        if( chkAuth.Checked )
                        {
                            oServer.User = textUser.Text;
                            oServer.Password = textPassword.Text;
                        }

                        if( chkSSL.Checked )
                            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    }
                    else
                    {
                        //To send email to the recipient directly(simulating the smtp server),
                        //please add a Received header,
                        //otherwise, many anti-spam filter will make it as junk email.
                        System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                        string gmtdate = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                        gmtdate.Remove( gmtdate.Length - 3, 1 );
                        string recvheader = String.Format( "from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                            oServer.HeloDomain,
                            gmtdate );

                        oMail.Headers.Insert( 0, new HeaderItem( "Received", recvheader ));
                    }

                     _CrossThreadSetItemText( "Connecting ...", index );

                    //Catching the following events is not necessary,
                    //just make the application more user friendly.
                    //If you use the object in asp.net/windows service or non-gui application,
                    //You need not to catch the following events.
                    //To learn more detail, please refer to the code in EASendMail EventHandler region
                    oSmtp.OnIdle += new SmtpClient.OnIdleEventHandler( OnIdle );
                    oSmtp.OnAuthorized += new SmtpClient.OnAuthorizedEventHandler( OnAuthorized );
                    oSmtp.OnConnected += new SmtpClient.OnConnectedEventHandler( OnConnected );
                    oSmtp.OnSecuring += new SmtpClient.OnSecuringEventHandler( OnSecuring );
                    oSmtp.OnSendingDataStream += new SmtpClient.OnSendingDataStreamEventHandler( OnSendingDataStream );

                    SmtpClientAsyncResult oResult = null;
                    if( !chkTestRecipients.Checked )
                    {
                        oResult = oSmtp.BeginSendMail(
                            oServer, oMail,  null, null );
                    }
                    else
                    {
                        //Just test the email address without sending email data.
                        oResult = oSmtp.BeginTestRecipients(
                            null, oMail, null, null );
                    }

                    //Add the object instance to the array.
                    arSmtp[i] = oSmtp;
                    arResult[i] = oResult;
                    break;
                }
            }
        }