コード例 #1
0
ファイル: MailHelper.cs プロジェクト: mominbd/testing
    public static bool SendMail(string form, string to, string subject, string body)
    {
        bool valid = true;
        MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress(form);
        mailMessage.To.Add(to);
        mailMessage.Subject = subject;
        mailMessage.Body = body;

        SmtpClient smtpClient = new SmtpClient();

        try
        {
            smtpClient.EnableSsl = true;
            smtpClient.Send(mailMessage);
        }
        catch (Exception ex)
        {
            try
            {
                smtpClient.Send(mailMessage);
            }
            catch (Exception e)
            {
                valid = false;
                throw new Exception(e.Message, e.InnerException);
            }

            valid = false;

        }

        return valid;
    }
コード例 #2
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();

        //put the values taken from the text boxes in the
        //instance

        mail.To.Add("*****@*****.**");
        //  mail.From = new MailAddress(TextBox3.Text);
        mail.Subject = "Contact Form Message";
        mail.Body = TextBox4.Text;

        //string emailServer = "learn.senecac.on.ca";
        //checks whether the from text field is not empty
        //and it contains the "@" sign.
        // if (email.From != "" && email.From.Contains("@"))
        // {

        SmtpClient mysmtpclient = new SmtpClient("host");
        if (RadioButtonList1.SelectedIndex == 0)
        {

            mail.CC.Add(TextBox3.Text);
            mysmtpclient.Send(mail);

        }
        else { mysmtpclient.Send(mail); }
        //disables the text fields to prevent user input

        //txtEmailAddress.Enabled = false;
        //txtMessage.Enabled = false;
    }
コード例 #3
0
ファイル: Contact.aspx.cs プロジェクト: Jsisk/PersonalSite
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        /* This event handler will create and send an email message from one of our
         * CenteriqHosting email accounts. YOU CANNOT TEST IT LOCALLY.
         * But when the code is on our CentricHosting server, it will work because
         * it has permissions there to send the email.
         *
         * */

        //build the body of the email (to be used in our MailMessage object)
        string body = string.Format(
            "Name: <strong>{0}</strong> <br/>Email: <strong>{1}</strong><br />" +
            "Phone: <strong>{2}<strong><br/>Comments: <blockquote>{3}</blockquote>",
            tbName.Text, tbEmail.Text, tbPhone.Text, tbMessage.Text);

        MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**", "WG Message from " + tbName.Text, body);
            //first parameter is FROM address, need to be one of your centriqhosting emails
            //second param is where you want it sent

        //optionally add some properties
        msg.IsBodyHtml = true;//NOTE this doesn't let end-user type in HTML. It'd for
            //us, the developers, to include html.
        msg.Priority = MailPriority.High;

        //there are different ways to accomplish this, depending on the version of the
        //    .NET framework your host is using, but here's 1 way to set ReplyTo Property.
        MailAddress formFiller = new MailAddress(tbEmail.Text, tbName.Text);

        msg.ReplyTo = formFiller;

        //to SEND the message, we need an SMTP client OBJECT and to call it's Send();
        SmtpClient client = new SmtpClient("relay-hosting.secureserver.net");

        try
        {
            client.Send(msg);//this actually tries to send the message.

            //send the formfiller a confirmation message
            client.Send("*****@*****.**", tbEmail.Text, "Thanks!", "Thank you for your words! I'll get back to you as soon as i can. Have a good one! ~Jeren");

            //update the label with the confirmation
            lblConfirm.Text = "Your Email went through, I'll get to you as soon as I can :) thanks!";
        }
        catch (Exception)
        {

            lblConfirm.Text = "Sorry, there was some sort of error. There is a large room full of robots working on the problem right now.";

        }

        //clear fields

        tbMessage.Text = "";
        tbEmail.Text = "";
        tbName.Text = "";
        tbConfirmEmail.Text = "";
        tbPhone.Text = "";

        mvContact.SetActiveView(vwConfirm);
    }
コード例 #4
0
        public static void Run()
        {
            // ExStart:SupportIMAPIdleCommand
            // Connect and log in to IMAP 
            ImapClient client = new ImapClient("imap.domain.com", "username", "password");

            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            ImapMonitoringEventArgs eventArgs = null;
            client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e)
            {
                eventArgs = e;
                manualResetEvent.Set();
            });
            Thread.Sleep(2000);
            SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(10000);
            manualResetEvent.Reset();
            Console.WriteLine(eventArgs.NewMessages.Length);
            Console.WriteLine(eventArgs.DeletedMessages.Length);
            client.StopMonitoring("Inbox");
            smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command"));
            manualResetEvent.WaitOne(5000);
            // ExEnd:SupportIMAPIdleCommand
        }
コード例 #5
0
ファイル: al.cs プロジェクト: pchnet/SQLServer
    public static bool EmailAlert(string to_add, string from_add, string em_sub, string em_bd, string smtp_server = null, string sAttachment = null)
    {
        int i = 0;
        string[] sTempA = null;
        SmtpClient SmtpMail = new SmtpClient();
        MailMessage MailMsg = new MailMessage();

        sTempA = to_add.Split(',');

        try
        {
            for (i = 0; i < (sTempA.Length -1); i++)
            {
                MailMsg.To.Add(new MailAddress(sTempA[i]));
            }

            MailMsg.From = new MailAddress(from_add);
            MailMsg.Subject = em_sub.Trim();
            MailMsg.Body = em_bd.Trim() + Environment.NewLine;

            if (sAttachment != null)
            {
                Attachment MsgAttach = new Attachment(sAttachment);
                MailMsg.Attachments.Add(MsgAttach);

                if (smtp_sender == null)
                {
                    // default
                    SmtpMail.Host = "";
                }
                else
                {
                    SmtpMail.Host = smtp_sender;
                }
                SmtpMail.Send(MailMsg);
                MsgAttach.Dispose();
            }
            else
            {
                SmtpMail.Host = smtp_sender;
                SmtpMail.Send(MailMsg);
            }
            return true;
        }
        catch (Exception ex)
        {
            sTempA = null;
            SmtpMail.Dispose();
            MailMsg.Dispose();
            //Console.WriteLine(ex);
            return false;
        }
    }
コード例 #6
0
    protected void Signup_Click(object sender, EventArgs e)
    {
        MembershipUser membershipuser;
        MembershipCreateStatus membershipcreatestatus;
        ProfileCommon profilecommon;
        MailMessage mailmessagetouser, mailmessagetoadministrator;
        NetworkCredential networkcredential;
        SmtpClient smtpclient;

        if (ValidateInput())
        {
            try
            {
                membershipuser = Membership.CreateUser(EmailAddress.Text, "user@pass", EmailAddress.Text, "Password Question", "Password Answer", false, out membershipcreatestatus);

                profilecommon = (ProfileCommon)ProfileCommon.Create(EmailAddress.Text, true);
                profilecommon.InstituteAdministrator.Name = Name.Text;
                profilecommon.InstituteAdministrator.Description = Description.Text;
                profilecommon.InstituteAdministrator.Street = Street.Text;
                profilecommon.InstituteAdministrator.HouseNumber = HouseNumber.Text;
                profilecommon.InstituteAdministrator.City = City.Text;
                profilecommon.InstituteAdministrator.Country = Country.Text;
                profilecommon.InstituteAdministrator.PostalCode = PostalCode.Text;

                profilecommon.Save();

                Roles.AddUserToRole(EmailAddress.Text, GlobalVariable.instituteadministratorrolename);

                mailmessagetouser = new MailMessage(GlobalVariable.superadministratoremailaddress, EmailAddress.Text, "Email Subject", GlobalVariable.emailheadertemplate + "<p>Email Body</p>" + GlobalVariable.emailfootertemplate);
                mailmessagetouser.IsBodyHtml = true;
                mailmessagetoadministrator = new MailMessage(GlobalVariable.superadministratoremailaddress, GlobalVariable.superadministratoremailaddress, "Email Subject", GlobalVariable.emailheadertemplate + "<p>Email Body</p><p>Approval Link : <a href=\"" + Request.Url.GetLeftPart(UriPartial.Authority) + Page.ResolveUrl("~/registrationcomplete.aspx?operation=instituteregistrationrequestapprove&username="******"\">Approve Account</a></p>" + GlobalVariable.emailfootertemplate);
                mailmessagetoadministrator.IsBodyHtml = true;
                networkcredential = new NetworkCredential(GlobalVariable.superadministratoremailaddress, GlobalVariable.superadministratoremailpassword);
                smtpclient = new SmtpClient("smtp.mail.yahoo.com", 587);
                smtpclient.UseDefaultCredentials = false;
                smtpclient.Credentials = networkcredential;
                smtpclient.Send(mailmessagetouser);
                smtpclient.Send(mailmessagetoadministrator);

                Response.Redirect("registrationcomplete.aspx?operation=instituteregistrationrequest");
            }
            catch (Exception exception)
            {

            }
        }
        else
        {

        }
    }
コード例 #7
0
ファイル: news.aspx.cs プロジェクト: pmstrategygroup/osi
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (Request.Form.Count > 0)
            {
                try
                {
                    SmtpClient client = new SmtpClient();
                    var mail = new MailMessage(ConfigurationManager.AppSettings["FormEmailFrom"], ConfigurationManager.AppSettings["FormEmailTo"]);
                    mail.Subject = "New OSI Contact Form Submission";
                    mail.Body = "Name: " + Request.Form["name"] + "\n" +
                                          "Email: " + Request.Form["email"] + "\n" +
                                          "Message: " + Request.Form["message"];

                    client.Send(mail);

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "onContact()", true);
                }
                catch (Exception)
                {

                }
            }
        }
    }
コード例 #8
0
    public bool sendMail(EmailModel emailModel)
    {
        MailMessage mail = new MailMessage();
        SmtpClient client = new SmtpClient();
        client.Port = 587;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Host = "smtp.gmail.com";
        mail.To.Add(new MailAddress("*****@*****.**"));
        mail.From = new MailAddress("*****@*****.**");
        client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "haythamfaraz");
        mail.Subject = emailModel.name + " | " + emailModel.service;
        client.EnableSsl = true;
        mail.IsBodyHtml = true;
        mail.Body = "<html>"
+ "<body>"
+ "<div> <h2>Email: " + emailModel.email + " </h2> </br>"
+ "<h2> Name: " + emailModel.name + "</h2> </br>" +
"<h2> Phone number: " + emailModel.phoneNumber + "</h2> </br>" +
"<h2> Service: " + emailModel.service + "</h2> </br>" +
"<h2> More Information: " + emailModel.message + "</h2> </br>"
+ "</div>"
+ "</body>"
+ "</html>";
        try
        {
            client.Send(mail);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
コード例 #9
0
ファイル: Default3.aspx.cs プロジェクト: Angliy/DemoForTest
    /// <summary>
    /// 外发邮件支持群发
    /// </summary>
    /// <param name="MessageFrom">发件人</param>
    /// <param name="MessageTo">群发多用户使用"|"格开地址</param>
    /// <param name="MessageSubject">邮件主题</param>
    /// <param name="MessageBody">邮件内容</param>
    /// <returns>是否发送成功</returns>
    public bool SendMail(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody)
    {
        MailMessage message = new MailMessage();

        message.From = MessageFrom;

        string[] mtuser = MessageTo.Split('|');
        foreach (string m in mtuser)
        {
            message.To.Add(m);
        }

        message.Subject = MessageSubject;
        message.Body = MessageBody;
        message.IsBodyHtml = true;              //是否为html格式
        message.Priority = MailPriority.High;   //发送邮件的优先等级

        SmtpClient sc = new SmtpClient("smtp.gmail.com"); //指定发送邮件的服务器地址或IP

        sc.Port = 587;   //指定发送邮件端口
        sc.EnableSsl = true;
        sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "000000"); //指定登录服务器的用户名和密码
        //try
        //{
            sc.Send(message);       //发送邮件
        //}
        //catch
        //{
        //    return false;
        //}
        return true;
    }
コード例 #10
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Set up SMTP client
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = int.Parse("587");
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.Credentials = new NetworkCredential("p.aravinth.info", "Pakashrn@6");
        client.EnableSsl = true;

        //Set up the email message
        MailMessage message = new MailMessage();
        message.To.Add("*****@*****.**");
        message.To.Add("*****@*****.**");
        message.From = new MailAddress("*****@*****.**");
        message.Subject = " MESSAGE FROM WWW.ARAVINTH.INFO ";
        message.IsBodyHtml = true; //HTML email
        message.Body = "Sender Name : " + sender_name.Text + "<br>"
            + "Sender Email : " + sender_email.Text + "<br>" + "Sender Message : " + sender_msg.Text + "<br>";
           

        //Attempt to send the email
        try
        {

            client.Send(message);

            status.Text = "Your Message has been Successfully Sent... I'll Contact You As Soon as possible..";
        }
        catch (Exception ex)
        {
            status.Text = "There was an error while sending the message... Please Try again";
        }
    }
コード例 #11
0
    public void sendmail(string idinmueble, string mail, string emailAlternativo, string calles, string numero)
    {
        //Primero debemos importar los namespace

        //El metodo que envia debe contener lo siguiente
        MailMessage objEmail = new MailMessage();
        objEmail.From = new MailAddress("*****@*****.**");
        objEmail.ReplyTo = new MailAddress("*****@*****.**");
        //Destinatario
        objEmail.To.Add(mail);
        //objEmail.To.Add(mail1);
        if (emailAlternativo != "")
        {
            objEmail.CC.Add(emailAlternativo);
        }
        objEmail.Bcc.Add("*****@*****.**");
        objEmail.Priority = MailPriority.Normal;
        //objEmail.Subject = "hola";
        objEmail.IsBodyHtml = true;
        objEmail.Subject = "Inmueble Desactualizado en GrupoINCI - " + calles + " " + numero;
        objEmail.Body = htmlMail(idinmueble);
        SmtpClient objSmtp = new SmtpClient();
        objSmtp.Host = "localhost ";
        objSmtp.Send(objEmail);
    }
コード例 #12
0
 public bool sendmail(string subject, string body)
 {
     try
     {
         string mailstring = "";
         string host = "";
         string pass = "";
         IDataReader reader = ((IDataReader)((IEnumerable)SqlDataSource6.Select(DataSourceSelectArguments.Empty)));
         while (reader.Read())
         {
             mailstring = reader["send_mail"].ToString();
             pass = reader["pass"].ToString();
             host = reader["host"].ToString();
         }
         SmtpClient SmtpServer = new SmtpClient();
         SmtpServer.Credentials = new System.Net.NetworkCredential(mailstring, pass);
         SmtpServer.Port = 25;
         SmtpServer.Host = host;
         SmtpServer.EnableSsl = false;
         MailMessage mail = new MailMessage();
         mail.From = new MailAddress(mailstring);
         mail.To.Add(mailstring);
         mail.Subject = subject;
         mail.Body = body;
         mail.IsBodyHtml = true;
         SmtpServer.Send(mail);
         return true;
     }
     catch
     {
         return false;
     }
 }
コード例 #13
0
    private void Mail_Gonder(string gonderen, string gonderen_sifre, string alan, string baslik, string icerik)
    {
        string smtpAddress = "smtp.gmail.com";
        int portNumber = 587;
        bool enableSSL = true;

        string emailFrom = gonderen;
        string password = gonderen_sifre;
        string emailTo = alan;
        string subject = baslik;
        string body = icerik;

        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            // Can set to false, if you are sending pure text.

            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }

        }
    }
コード例 #14
0
    public void goodCode()
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        try
        {
            MailAddress fromAddress = new MailAddress("*****@*****.**", "Jovino");

            smtpClient.Host = "smtpout.secureserver.net";
            smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "tim052982");

            Response.Write("host " + smtpClient.Host);

            smtpClient.Port = 25;
            smtpClient.EnableSsl = false;
            message.From = fromAddress;

            message.To.Add("*****@*****.**");
            message.Subject = "Feedback";

            message.IsBodyHtml = false;

            message.Body = "Testing 123";

            smtpClient.Send(message);

            Response.Write("message sent right now!");

        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
コード例 #15
0
ファイル: Email.cs プロジェクト: jaroban/Web
 public void Send()
 {
     Result = "";
     Success = true;
     try
     {
         // send email
         var senderAddress = new MailAddress(SenderAddress, SenderName);
         var toAddress = new MailAddress(Address);
         var smtp = new SmtpClient
         {
             Host = SmtpServer,
             Port = SmtpPort,
             EnableSsl = true,
             DeliveryMethod = SmtpDeliveryMethod.Network,
             UseDefaultCredentials = false,
             Credentials = new NetworkCredential(senderAddress.Address, Password),
             Timeout = 5000
         };
         smtp.ServicePoint.MaxIdleTime = 2;
         smtp.ServicePoint.ConnectionLimit = 1;
         using (var mail = new MailMessage(senderAddress, toAddress))
         {
             mail.Subject = Subject;
             mail.Body = Body;
             mail.IsBodyHtml = true;
             smtp.Send(mail);
         }
     }
     catch(Exception ex)
     {
         Result = ex.Message + " " + ex.InnerException;
         Success = false;
     }
 }
コード例 #16
0
ファイル: Email.cs プロジェクト: scottbeachy/WEB460
    public void Send(string fName, string lName, string email, string addr, string city, string state, string zip, string ccnum, string exp)
    {
        string _fName = fName;
        string _lName = lName;
        string _addr = addr;
        string _city = city;
        string _state = state;
        string _zip = zip;
        string _ccnum = ccnum;
        string _exp = exp;
        string _email = email;

        MailMessage mail = new MailMessage("*****@*****.**", _email);

        StringBuilder sb = new StringBuilder();
        sb.Append("Order from " + _fName + " " + _lName);
        mail.Subject = sb.ToString();
        StringBuilder sb2 = new StringBuilder();
        sb2.Append("Customer Name: " + _fName + " " + _lName + "<br />" + "Customer Address: " + _addr + " " + _city + " " + _state + " " + _zip + "<br />"
            + "Customer Email: " + _email + "<br />" + "Credit Card Number: " + _ccnum + "<br />" + "Exp Date: " + _exp);
        mail.Body = sb2.ToString();
        mail.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient("localhost");
        smtp.Send(mail);
    }
コード例 #17
0
    public void Submit_Click(object sender, EventArgs e)
    {
        try
        {
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);

            smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "NenDdjlbnczNtrcn5483undSend3n");
            smtpClient.UseDefaultCredentials = false;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.EnableSsl = true;
            MailMessage mail = new MailMessage();

            //Setting From , To and CC
            mail.From = new MailAddress(txtemail.Text);
            mail.To.Add(new MailAddress("*****@*****.**"));
            mail.CC.Add(new MailAddress("*****@*****.**"));
            mail.Subject = txtsubject.Text+" "+txtcmpnm.Text+" "+txtName.Text;
            mail.Body = txtmsg.Text;

            smtpClient.Send(mail);
        }
        catch (Exception ee)
        {
        }
    }
コード例 #18
0
ファイル: Mail.cs プロジェクト: rajarupinder/FBL
    public void SendScheduleMail(string name, string email, string username, string password)
    {
        try
        {
            MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            message.From = new MailAddress("*****@*****.**", "FBL");
            message.To.Add(new MailAddress(email));
            message.IsBodyHtml = true;
            message.Subject = "FBL Updates";
            message.Body = @"<b>Hello " + name + ",</b><br /><br />" +
                                "Please click on the below link<br />" +
                                "http://gpsworld.us/FBL/Default.aspx?uid=" + Convert.ToBase64String(Encoding.Unicode.GetBytes(username)) + "&pid=" + Convert.ToBase64String(Encoding.Unicode.GetBytes(password));

            message.Priority = MailPriority.High;
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "17585@LPU");
            smtp.Send(message);
        }
        catch
        {

        }
    }
コード例 #19
0
ファイル: Default.aspx.cs プロジェクト: LuxF3rre/Jquery-Files
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     try
     {
         MailMessage Msg = new MailMessage();
         // Sender e-mail address.
         Msg.From = new MailAddress(txtEmail.Text);
         // Recipient e-mail address.
         Msg.To.Add("*****@*****.**");
         Msg.Subject = txtSubject.Text;
         Msg.Body = txtMessage.Text;
         // your remote SMTP server IP.
         SmtpClient smtp = new SmtpClient();
         smtp.Host = "smtp.gmail.com";
         smtp.Port = 587;
         smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "123jakes123");
         smtp.EnableSsl = true;
         smtp.Send(Msg);
         //Msg = null;
         lbltxt.Text = "Thanks for Contact us";
         // Clear the textbox valuess
         txtName.Text = "";
         txtSubject.Text = "";
         txtMessage.Text = "";
         txtEmail.Text = "";
     }
     catch (Exception ex)
     {
         Console.WriteLine("{0} Exception caught.", ex);
     }
 }
コード例 #20
0
ファイル: subscribeMail.cs プロジェクト: vyeluri/bbcDemoSite
    public void Sendsubscribe(String to, String msgSub)
    {
        try
        {
            MailMessage msg = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            msg.From = new MailAddress("*****@*****.**");
            msg.To.Add(new MailAddress(to));

            msg.Bcc.Add(new MailAddress("*****@*****.**"));
            msg.Subject = msgSub;
            msg.Body = "Hello," + "<br /><br /> Thank You for subscribing to our news letters. We will inform you for our every update. <br /><br/> Regards <br />V!";
            msg.IsBodyHtml = true;

            //Name the client which you will be using to send email.
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Sairam)9");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(msg);
        }
        catch (Exception ex)
        {
            //label = ex.Message;
        }
    }
コード例 #21
0
    public static void Send(string to, string title, string body)
    {
        MailMessage mail = new MailMessage();

        MailAddress address = new MailAddress(to);

        MailAddress FromAddress = new MailAddress("*****@*****.**", "vbn");

        mail.From = FromAddress;

        mail.To.Add(address);

        mail.Body = body;

        mail.Subject = title;

        mail.BodyEncoding = Encoding.UTF8;

        SmtpClient SendMail = new SmtpClient();

        NetworkCredential Authentication = new NetworkCredential();

        Authentication.UserName = "******";

        Authentication.Password = "******";

        SendMail.Credentials = Authentication;

        SendMail.Host = "mail.vbn.vn";

        SendMail.Port = 25;

        SendMail.Send(mail);
    }
コード例 #22
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string fileName = Server.MapPath("~/APP_Data/ContactForm.txt");
            string mailBody = File.ReadAllText(fileName);

            mailBody = mailBody.Replace("##Name##", txbxName.Text);
            mailBody = mailBody.Replace("##Email##", txbxMail.Text);
            mailBody = mailBody.Replace("##Phone##", txbxPhone.Text);
            mailBody = mailBody.Replace("##Comments##", txbxComents.Text);

            MailMessage myMessage = new MailMessage();
            myMessage.Subject = "Comentario en el Web Site";
            myMessage.Body = mailBody;
            myMessage.From = new MailAddress("*****@*****.**", "Uge Pruebas");
            myMessage.To.Add(new MailAddress("*****@*****.**", "Eugenio"));
            myMessage.ReplyToList.Add(new MailAddress(txbxMail.Text));
            SmtpClient mySmtpClient = new SmtpClient();
            mySmtpClient.Send(myMessage);

            laMessageSent.Visible=true;
            MessageSentPara.Visible = true;
            FormTable.Visible = false;
        }
    }
コード例 #23
0
        public static void Run()
        {
            // ExStart:SendingBulkEmails
            // Create SmtpClient as client and specify server, port, user name and password
            SmtpClient client = new SmtpClient("mail.server.com", 25, "Username", "Password");

            // Create instances of MailMessage class and Specify To, From, Subject and Message
            MailMessage message1 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject1", "message1, how are you?");
            MailMessage message2 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject2", "message2, how are you?");
            MailMessage message3 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject3", "message3, how are you?");

            // Create an instance of MailMessageCollection class
            MailMessageCollection manyMsg = new MailMessageCollection();
            manyMsg.Add(message1);
            manyMsg.Add(message2);
            manyMsg.Add(message3);

            // Use client.BulkSend function to complete the bulk send task
            try
            {
                // Send Message using BulkSend method
                client.Send(manyMsg);                
                Console.WriteLine("Message sent");
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            // ExEnd:SendingBulkEmails
        }
コード例 #24
0
    public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
    {
        try
        {
            NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(gMailAccount);
            msg.To.Add(new MailAddress(to));
            msg.Subject = subject;
            msg.Body = message;
            msg.IsBodyHtml = true;
            SmtpClient client = new SmtpClient("smtp.gmail.com");
            client.Port = 587;
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = loginInfo;
            client.Send(msg);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
コード例 #25
0
    private void SendEmail()
    {
        String content = string.Empty;

        var objEmail = new MailMessage();
        objEmail.From = new MailAddress("*****@*****.**", "Sender");

        objEmail.Subject = "Test send email on GoDaddy account";
        objEmail.IsBodyHtml = true;

        var smtp = new SmtpClient();
        smtp.Host = "smtpout.secureserver.net";
        smtp.Port = 80;
        smtp.EnableSsl = false;
        // and then send the mail
        //        ServicePointManager.ServerCertificateValidationCallback =
        //delegate(object s, X509Certificate certificate,
        //X509Chain chain, SslPolicyErrors sslPolicyErrors)
        //{ return true; };

        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        //smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "#passw0rd#");

        objEmail.To.Add("*****@*****.**");
         objEmail.To.Add("*****@*****.**");
        objEmail.Body = content;

        smtp.Send(objEmail);
    }
コード例 #26
0
        public static void Run()
        {
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_SMTP();
            string dstEmail = dataDir + "Message.eml";

            // Create an instance of the MailMessage class
            MailMessage message = new MailMessage();

            // Import from EML format
            message = MailMessage.Load(dstEmail, new EmlLoadOptions());

            // Create an instance of SmtpClient class
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "*****@*****.**", "your.password");
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Client.Send will send this message
                client.Send(message);
                Console.WriteLine("Message sent");
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
            }
            Console.WriteLine(Environment.NewLine + "Email sent using EML file successfully. " + dstEmail);
        }
コード例 #27
0
    public void sendEmail(String aemailaddress, String asubject, String abody)
    {
        try
        {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            MailAddress from = new MailAddress("*****@*****.**", "123");
            MailAddress to = new MailAddress(aemailaddress, "Sas");
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail message sent using gmail as a relay server ";
            message.Subject = "Gmail test email with SSL and Credentials";
            NetworkCredential myCreds = new NetworkCredential("*****@*****.**", "", "");
            client.Credentials = myCreds;

            client.Send(message);
            Label1.Text = "Mail Delivery Successful";
        }
        catch (Exception e)
        {
            Label1.Text = "Mail Delivery Unsucessful";
        }
        finally
        {
            txtUserID.Text = "";
            txtQuery.Text = "";
        }
    }
コード例 #28
0
ファイル: PESMails.cs プロジェクト: lengocluyen/pescode
 public static bool Send(PESMail mail)
 {
     SmtpClient smtp = new SmtpClient();
     smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings.Get("Sender"), ConfigurationManager.AppSettings.Get("MailPass"));
     smtp.Host = ConfigurationManager.AppSettings.Get("SmtpHost");
     smtp.Port = Commons.ConvertToInt(ConfigurationManager.AppSettings.Get("SmtpPort"),25);
     smtp.EnableSsl = true;
     using (MailMessage message = new MailMessage())
     {
         message.From = new MailAddress(ConfigurationManager.AppSettings.Get("defaultSender"));
         for (int i = 0; i < mail.List.Count;i++ )
         {
             message.To.Add(mail.List[i].ToString());
         }
         message.Subject = mail.Subject;
         message.Body = mail.Content;
         message.IsBodyHtml = mail.IsHtml;
         try
         {
             smtp.Send(message);
             return true;
         }
         catch
         {
             return false;
         }
     }
 }
    //protected void gridView_Load(object sender, EventArgs e)
    //{
    //    for (int i = 0; i < GridView1.Rows.Count; i++)
    //    {
    //        if ((DateTime.Parse(GridView1.Rows[i].Cells[2].Text)) < (DateTime.Parse(DateTime.Today.ToShortDateString())))
    //        {
    //            GridView1.Rows[i].Visible = false;
    //            //GridView1.da
    //        }
    //    }
    //}
    protected void Button1_Click(object sender, EventArgs e)
    {
        MyService.UserWebService uws = new UserWebService();
        uws.Credentials = System.Net.CredentialCache.DefaultCredentials;
        int id = uws.getAppointmentID(Int32.Parse(DropDownList1.SelectedValue), DateTime.Parse(Label1.Text));
        int status = 1;
        uws.makeStudentAppointment(id, sid, txtSubject.Text, DateTime.Parse(DropDownList2.SelectedValue), DateTime.Parse(txtEndtime.Text), status);
        //   SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        //smtp.UseDefaultCredentials = false;
        //smtp.Credentials = new NetworkCredential("*****@*****.**","were690vase804");
        //smtp.EnableSsl = true;
        //smtp.Send("*****@*****.**", "*****@*****.**", "Appointment", "Appointment Successfull");

        MailAddress mailfrom = new MailAddress("*****@*****.**");
        MailAddress mailto = new MailAddress("*****@*****.**");
        MailMessage newmsg = new MailMessage(mailfrom, mailto);

        newmsg.Subject = "APPOINTMENT";
        newmsg.Body = "Appointment Successful";

        //    Attachment att = new Attachment("C:\\...file path");
          //  newmsg.Attachments.Add(att);

        SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("*****@*****.**","were690vase804");
        smtp.EnableSsl = true;
        smtp.Send(newmsg);
        Response.Write(@"<script language='javascript'>alert('Appointment Made and Confirmation has been sent to your mail')</script>");
    }
コード例 #30
0
ファイル: Utilities.cs プロジェクト: cleancodelover/Teachify
        /// <summary>
        /// This method sends an email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool SendMail(string Receiver = null, string body = null, string attachmentUrl = null, string subject = null)
        {
            bool result = false;

            if (!string.IsNullOrEmpty(Receiver) && !string.IsNullOrEmpty(body))
            {
                string From = "*****@*****.**"; //example:- [email protected]
                string PW   = "Pa$$w00rd";
                try
                {
                    using (MailMessage mail = new MailMessage(From, Receiver))
                    {
                        mail.Subject = subject;

                        StringBuilder sb = new StringBuilder();
                        sb.Append(body);
                        mail.Body = sb.ToString();
                        if (!string.IsNullOrEmpty(attachmentUrl))
                        {
                            string fileName = Path.GetFileName(attachmentUrl);
                            mail.Attachments.Add(new Attachment(attachmentUrl));
                        }

                        mail.IsBodyHtml = true;

                        SmtpClient smtpClient = new SmtpClient();
                        smtpClient.UseDefaultCredentials = true;
                        smtpClient.Host        = "5.77.48.66";
                        smtpClient.Port        = 25;
                        smtpClient.EnableSsl   = false;
                        smtpClient.Credentials = new NetworkCredential(From, PW);

                        ServicePointManager.ServerCertificateValidationCallback =
                            delegate(object s, X509Certificate certificate,
                                     X509Chain chain, SslPolicyErrors sslPolicyErrors)
                        { return(true); };
                        try
                        {
                            smtpClient?.Send(mail);
                            result = true;
                            //client.Send(mail);
                        }
                        catch (Exception ex)
                        {
                            return(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(result);
                }
            }
            return(result);
        }
コード例 #31
0
        public void Send()
        {
//			Mail.Subject = "Student Ticket Code";
//			Mail.Body = string.Format(
//@"This email is a response to a request for a student discount code. We have validated your email address and are pleased to offer you this code.

//This code is tied to your email address is a valid for one use. If you misplace this email, you may supply your email to the DevSpace website on the tickets page to receive another copy of this email. A new code will not be generated.

//You may go directly to out ticketing page using the link below.

//https://www.eventbrite.com/e/devspace-2016-registration-24347789895?access={0}

//If you wish, you may also go directly to EventBrite, find out event, and manually enter the code:

//{0}

//We thank you for your interest in the DevSpace Technical Conference and look forward to seeing you there.", studentCode.Code );

            Client?.Send(Mail);
        }
コード例 #32
0
        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int    received; student stud;

            try
            {
                received = current.EndReceive(AR);
                if (received != 0)
                {
                    byte[] recBuf = new byte[received];
                    Array.Copy(_buffer, recBuf, received);
                    string   text    = Encoding.UTF8.GetString(recBuf);
                    string[] details = Encoding.ASCII.GetString(recBuf).Split(',');

                    string studId      = details[1];
                    string studEmail   = details[2];
                    string password    = "******";
                    string passEncoded = Methods.Encode(password);

                    student std = students.FirstOrDefault <student>(c => c.Num_ID.Equals(studId) && c.Email.Equals(studEmail));
                    //student stud = (student)dGrid.SelectedItem;
                    if (std != null)
                    {
                        List <dynamic> lastId = new List <dynamic>();
                        string         query  = "INSERT INTO devicereg(password) VALUE('" + passEncoded + "')";
                        Methods.updateOrInsertIntoTable(query);
                        query  = "SELECT devicereg_id FROM devicereg ORDER BY devicereg_id DESC limit 1";
                        lastId = Methods.selectFromDbs(query);
                        query  = "UPDATE students  SET devicereg_id =" + lastId[0] + " WHERE student_id = " + std.ID;
                        Methods.updateOrInsertIntoTable(query);
                        std.password = password;

                        using (MailMessage mail = new MailMessage())
                        {
                            mail.From = new MailAddress("*****@*****.**");
                            mail.To.Add(std.Email);
                            mail.Subject = "Fjalekalimi per evidencen";
                            mail.Body    = "Ky eshte fjalekalimi juaj: " + password;

                            using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                            {
                                smtp.Credentials = new NetworkCredential("*****@*****.**", "Jimmy123");
                                smtp.EnableSsl   = true;
                                smtp.Send(mail);
                            }
                        }
                    }

                    if (details[0].Equals("student"))
                    {
                        studId = details[1];
                        string studPass   = details[2];
                        string studPassEn = Methods.Encode(studPass);
                        std = students.FirstOrDefault <student>(c => c.password.Equals(studPassEn) && c.Num_ID.Equals(studId));

                        if (std != null)
                        {
                            byte[] data   = Encoding.UTF8.GetBytes("vazhdo");
                            int    length = data.Length;
                            //current.Send(Encoding.UTF8.GetBytes(length.ToString()));
                            current.Send(data);
                        }
                    }

                    if (details[0].Equals("device"))
                    {
                        string device_id = details[1];
                        studId = details[2];
                        stud   = students.FirstOrDefault <student>(c => c.Num_ID.Equals(studId));
                        if (stud != null)
                        {
                            string deviceNum     = "";
                            string deviceExistsQ = "SELECT * FROM devicereg WHERE device1='" + device_id + "' OR device2='" + device_id + "' OR device3='" + device_id + "' ";
                            bool   deviceExists  = Methods.existsInDBS(deviceExistsQ);
                            bool   freeSpotAndDeviceNotRegistered = (String.IsNullOrEmpty(stud.device1) || String.IsNullOrEmpty(stud.device2) || String.IsNullOrEmpty(stud.device3)) && (!deviceExists);
                            Debug.WriteLine("Gati me hi");
                            if (freeSpotAndDeviceNotRegistered)
                            {
                                Debug.WriteLine("Hini");
                                if (String.IsNullOrEmpty(stud.device1))
                                {
                                    deviceNum    = "device1";
                                    stud.device1 = device_id;
                                }
                                else if (String.IsNullOrEmpty(stud.device1))
                                {
                                    deviceNum    = "device2";
                                    stud.device2 = device_id;
                                }
                                else if (String.IsNullOrEmpty(stud.device1))
                                {
                                    deviceNum    = "device3";
                                    stud.device3 = device_id;
                                }
                                if (!(String.IsNullOrEmpty(deviceNum)))
                                {
                                    string query = "UPDATE devicereg SET `" + deviceNum + "`='" + device_id + "' WHERE devicereg_id='" + stud.devicereg_id + "' ";
                                    Methods.updateOrInsertIntoTable(query);
                                }
                                byte[] data   = Encoding.UTF8.GetBytes("vazhdo");
                                int    length = data.Length;
                                //current.Send(Encoding.UTF8.GetBytes(length.ToString()));
                                current.Send(data);
                            }
                            else
                            {
                                Debug.WriteLine("S'hini");
                            }
                        }
                    }

                    stud = students.FirstOrDefault <student>(c => c.device1.Equals(details[1]) || c.device2.Equals(details[1]) || c.device3.Equals(details[1]));

                    //unkoment
                    if (stud != null)//details[0].Equals("student"))
                    {
                        stud.ip_Address     = current.RemoteEndPoint.ToString();
                        stud.isPresent      = true;
                        stud.countPresence += 1;

                        //unkoment
                        if (false)//!eW.students.Any<Student>(c => c.Id.ToString().Equals(details[1].Trim())))
                        {
                            //unkoment
                            MessageBox.Show("true");
                            klientet.Add(current);
                            //studentet.Add(new Student { Nr = count, Id = int.Parse(details[1]), Emri = details[2], Mbiemri = details[3], Check = "+(A)", countPresence = 1 });
                            //count++;
                            //eW.showStudentet(details);
                        }
                        else
                        {
                            // unkoment
                            //byte[] data = Encoding.UTF8.GetBytes("exists");
                            //int length = data.Length;
                            //current.Send(Encoding.UTF8.GetBytes(length.ToString()));
                            //current.Send(data);
                        }
                    }
                    if (details[0].Equals("here"))
                    {
                        //var user = studentet.Single(x => x.Id == int.Parse(details[1].Trim()));
                        //user.countPresence = user.countPresence + 1;
                        //MessageBox.Show("Student " + details[1] + "is here" + user.countPresence);
                    }
                    if (false)//text.Equals(eW.validateStudent))
                    {
                        // unkoment
                        //byte[] data = Encoding.UTF8.GetBytes(defaultMessage);
                        //int length = data.Length;
                        //current.Send(Encoding.UTF8.GetBytes(length.ToString()));
                        //current.Send(data);
                    }
                    else
                    {
                        //foreach (var item in details)
                        //    MessageBox.Show(item.ToString());
                        byte[] data   = Encoding.ASCII.GetBytes("mbyll");
                        int    length = data.Length;
                        //current.Send(Encoding.UTF8.GetBytes(length.ToString()));
                        //current.Send(data);
                    }
                    current.BeginReceive(_buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
                }
                else
                {
                    try
                    {
                        //MessageBox.Show("Studenti " + current.LocalEndPoint.ToString() + " u diskonenkt");
                        stud = students.FirstOrDefault <student>(c => c.ip_Address.Equals(current.RemoteEndPoint.ToString()));
                        current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
                                         //klientet.Remove(current);
                        if (stud != null)
                        {
                            stud.isPresent = false;
                        }
                    }
                    catch { }
                }
            }
            catch (SocketException ex)
            {
                //MessageBox.Show(ex.Message);
                //MessageBox.Show("Studenti " + current.LocalEndPoint + " u diskonenkt");
                stud = students.FirstOrDefault <student>(c => c.ip_Address.Equals(current.RemoteEndPoint.ToString()));
                if (stud != null)
                {
                    stud.isPresent = false;

                    //eW.Dispatcher.Invoke(() =>
                    //{
                    //    int dd = eW.listBox.Items.IndexOf(stu.name);
                    //    eW.listBox.Items.RemoveAt(dd);
                    //});
                }
                current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
                //klientet.Remove(current);
                return;
            }
        }
コード例 #33
0
ファイル: CourseDetails.aspx.cs プロジェクト: kstengle/sites
    /// <summary>
    /// Sending a mail after adding a course to the system
    /// </summary>
    /// <param name="course">Details of the course for sending email</param>
    /// <param name="stateProvince">State name</param>
    private void sendMail(Course course, string stateProvince)
    {
        //Provider provider = (Provider)Session[LACESConstant.SessionKeys.LOGEDIN_PROVIDER]; // get provider information from Session
        ApprovedProvider provider = (ApprovedProvider)Session[LACESConstant.SessionKeys.LOGEDIN_APPROVED_PROVIDER]; // get approved provider information from Session 
        string RefrenceURL = String.Empty;
        RefrenceURL = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.ToLower().LastIndexOf(LACESConstant.URLS.PROVIDER_BASE.ToLower())) + LACESConstant.URLS.ADMIN_BASE + "/" + LACESConstant.URLS.PENDING_COURSE;
        string courseDistance = string.Empty;
        if(course.DistanceEducation.Equals("Y"))
        {
            courseDistance = "Yes";
        }
        else
        {
            courseDistance = "No";
        }            
        if(course.StateProvince.Trim().Equals(string.Empty))
        {
            stateProvince = string.Empty;
        }

        StringBuilder EmailBody = new StringBuilder();
        EmailBody.Append("<table border='0' width='100%>");
        EmailBody.Append("<tr><td width='130'>&nbsp;</td><td>&nbsp;</td></tr>");
        EmailBody.Append("<tr><td colspan='2'>A new course has been added to the system by " + Server.HtmlEncode(provider.OrganizationName) + " and is <a href='" + RefrenceURL + "'>pending approval</a>. Please review the details of the course and either approve or reject the course.</td></tr>");
        EmailBody.Append("<tr><td colspan='2'><br/>The details of the new course are as follows:<br/></td></tr>");
        EmailBody.Append("<tr><td valign='top' width='130'>Course Title:</td><td>" + Server.HtmlEncode(course.Title) + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Course Hyperlink:</td><td>" + Server.HtmlEncode(course.Hyperlink) + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Start Date:</td><td>" + course.StartDate.ToString("MM/dd/yyyy") + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>End Date:</td><td>" + course.EndDate.ToString("MM/dd/yyyy") + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Description:</td><td>" + Server.HtmlEncode(course.Description) + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>City:</td><td>" + Server.HtmlEncode(course.City) + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>State:</td><td>" + Server.HtmlEncode(stateProvince) + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Distance Education:</td><td>" + courseDistance + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Subjects:</td><td>" + course.Subjects + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Health:</td><td>" + course.Healths + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Hours:</td><td>" + course.Hours + "</td></tr>");
        EmailBody.Append("<tr><td valign='top'>Learning Outcomes:</td><td>" + Server.HtmlEncode(course.LearningOutcomes) + "</td></tr>");
        EmailBody.Append("<tr><td colspan='2'><br/>If you wish to add this course to the " + LACESConstant.LACES_TEXT + " system, please <a href='" + RefrenceURL + "'>manage the list of pending courses</a> in the administration system to approve it.<br/></td></tr>");
        EmailBody.Append("<tr><td colspan='2'><br/>If you are going to reject the course, or wish to discuss the course further, please contact the course provider <a href='mailto:" + provider.ApplicantEmail + "'>via email</a>.<br/></td></tr>");
        EmailBody.Append("</table>");
        string mailBody = EmailBody.ToString();


        try
        {
            SmtpClient smtpClient = new SmtpClient();
            //Get the SMTP server Address from SMTP Web.conf
            smtpClient.Host = LACESUtilities.GetApplicationConstants(LACESConstant.SMTPSERVER);
            //Get the SMTP post  25;
            smtpClient.Port = Convert.ToInt32(LACESUtilities.GetApplicationConstants(LACESConstant.SMTPPORT));

            MailMessage message = new MailMessage();

            message.From = new MailAddress(LACESUtilities.GetAdminFromEmail());
            
            //message.To.Add(LACESUtilities.GetAdminToEmail());
            //message.CC.Add(LACESUtilities.GetAdminCCEmail());

            //Get the email's TO from Web.conf
            message.To.Add(LACESUtilities.GetCourseNotificationMailTo());

            message.Subject = "New Course Added - Pending Approval";
            message.IsBodyHtml = true;
            message.Body = mailBody;    // Message Body
            if (ConfigurationManager.AppSettings["SendOutgoingEmail"].ToString() == "Y")
            {
                smtpClient.Send(message);   //Sending A Mail to Admin
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
コード例 #34
0
        public OutputMessage SendMail(int indentId, string url)
        {
            DBManager db = new DBManager();

            try
            {
                //getting the email content from print page
                WebClient    client     = new WebClient();
                UTF8Encoding utf8       = new UTF8Encoding();
                string       htmlMarkup = utf8.GetString(client.DownloadData(url));

                //creating PDF
                HtmlToPdf   converter = new HtmlToPdf();
                PdfDocument doc       = converter.ConvertUrl(url);
                byte[]      bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    doc.Save(ms);
                    bytes = ms.ToArray();
                    ms.Close();
                    doc.DetachStream();
                }

                string query = @"select TagName,KeyID,KeyValue from TBL_SETTINGS where KeyID=106
                                 select TagName,KeyID,KeyValue from TBL_SETTINGS where KeyID=107
                                 select TagName,KeyID,KeyValue from TBL_SETTINGS where KeyID=108
                                 select TagName,KeyID,KeyValue from TBL_SETTINGS where KeyID=109";
                db.Open();
                DataSet     ds           = db.ExecuteDataSet(CommandType.Text, query);
                string      fromMail     = Convert.ToString(ds.Tables[0].Rows[0]["KeyValue"]);
                string      MailPassword = Convert.ToString(ds.Tables[1].Rows[0]["KeyValue"]);
                string      Host         = Convert.ToString(ds.Tables[2].Rows[0]["KeyValue"]);
                string      Port         = Convert.ToString(ds.Tables[3].Rows[0]["KeyValue"]);
                MailMessage mail         = new MailMessage();
                mail.From = new MailAddress(fromMail);

                if (!string.IsNullOrWhiteSpace(SupplierMail))
                {
                    mail.To.Add(this.SupplierMail);
                }
                if (!string.IsNullOrWhiteSpace(this.SupplierMailBCC))
                {
                    mail.Bcc.Add(this.SupplierMailBCC);
                }
                if (!string.IsNullOrWhiteSpace(SupplierMailCC))
                {
                    mail.CC.Add(SupplierMailCC);
                }
                mail.Body       = "Purchase Indent";
                mail.IsBodyHtml = false;
                mail.Subject    = "Invoice";
                mail.Attachments.Add(new Attachment(new MemoryStream(bytes), "Indent.pdf"));
                SmtpClient smtp = new SmtpClient()
                {
                    Host                  = Host,
                    EnableSsl             = true,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(fromMail, MailPassword),
                    Port                  = Convert.ToInt32(Port)
                };
                smtp.Send(mail);
                query = "update TBL_PURCHASE_INDENT_REGISTER set supplier_mail=@mail,SupplierCC_Mail=@SupplierCC_Mail,SupplierBCC_Mail=@SupplierBCC_Mail where pi_id=@indentId";
                db.CreateParameters(4);
                db.AddParameters(0, "@mail", this.SupplierMail);
                db.AddParameters(1, "@indentId", indentId);
                db.AddParameters(2, "@SupplierCC_Mail", this.SupplierMailCC);
                db.AddParameters(3, "@SupplierBCC_Mail", this.SupplierMailBCC);
                db.ExecuteNonQuery(CommandType.Text, query);
                return(new OutputMessage("Mail Send Successfully", true, Type.Others, "Purchase Indent | SendMail", System.Net.HttpStatusCode.InternalServerError));
            }
            catch (Exception ex)
            {
                return(new OutputMessage(ex.Message, false, Type.Others, "Purchase Indent | SendMail", System.Net.HttpStatusCode.InternalServerError, ex));
            }
            finally
            {
                db.Close();
            }
        }
コード例 #35
0
        public Asociado CrearAsociado(Asociado asociado)
        {
            bool     existe = true;
            Asociado creado = dao.getAsociado(asociado.CodigoModular, "");

            if (creado == null)
            {
                var token = Guid.NewGuid().ToString();
                asociado.Token = token;
                creado         = dao.insert(asociado);
                existe         = false;
            }
            if (creado != null)
            {
                try
                {
                    SmtpClient client = new SmtpClient();
                    client.Port                  = 587;
                    client.Host                  = "smtp.gmail.com";
                    client.EnableSsl             = true;
                    client.Timeout               = 10000;
                    client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "sitece$2019");
                    MailMessage mm = new MailMessage("*****@*****.**", asociado.Email, "Registro CITECE", "Su cuenta fue activada correctamente, su token es: <b>" + creado.Token + "</b>");
                    mm.BodyEncoding = UTF8Encoding.UTF8;
                    mm.IsBodyHtml   = true;
                    mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm);
                }
                catch { }
                if (existe)
                {
                    throw new FaultException <ManejadorException>(new ManejadorException()
                    {
                        Codigo      = "200",
                        Descripcion = "Código modular ya existe, se reenvió el token al correo " + creado.Email
                    }, new FaultReason("Error al intentar crea asociado"));
                }
            }
            return(creado);
        }
コード例 #36
0
    public void sendmail(String VV)
    {
        int i = 0;

        try
        {
            string hhhg = "SELECT    User_master.EmailID,  Login_master.username, Login_master.password, " +
                          " Login_master.department, Login_master.accesslevel, Login_master.deptid, Login_master.accessid, " +
                          " User_master.Name, Login_master.UserID " +
                          " FROM         Login_master LEFT OUTER JOIN " +
                          " User_master ON Login_master.UserID = User_master.UserID left outer join DepartmentmasterMNC on Login_master.department=DepartmentmasterMNC.Id " +
                          " Where User_master.UserId='" + Session["UserId"] + "'";
            SqlCommand cm = new SqlCommand(hhhg, con);
            cm.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(cm);
            DataTable      ds = new DataTable();
            da.Fill(ds);

            //StringBuilder HeadingTable = new StringBuilder();
            //HeadingTable = (StringBuilder)getSiteAddress();
            StringBuilder HeadingTable = new StringBuilder();
            HeadingTable = (StringBuilder)getSiteAddressWithWh();
            //lblHeading.Text = HeadingTable.ToString();
            //lblHeading.Visible = true;
            // string body = txtBody.Text;

            string AccountInfo = "";
            if (ds.Rows.Count > 0)
            {
                AccountInfo = " <b><span style=\"color: #996600\">ACCOUNT INFORMATION:</span></b><br><b>Username:</b><br>" + ds.Rows[0]["Name"].ToString() + "<br><b>Password:</b><br>" + ds.Rows[0]["password"].ToString() + " ";
            }


            string finalmessage = " Your Document " + VV + " Succcessfully";
            String body         = "" + HeadingTable + "<br><br> Dear " + ds.Rows[0]["Name"].ToString() + ",<br><br>" + finalmessage.ToString() + " <br>" + AccountInfo.ToString() + "<br><br><br> " +
                                  "<br><b>Customer Support:</b> " +
                                  " <br><br> " +
                                  " <span style=\"font-size: 10pt; color: #000000; font-family: Arial\"> " +
                                  "Sincerely,</span><br><strong><span style=\"color: #996600\"> " + ViewState["sitename"] + " " +
                                  " Team</span></strong>";

            string strmal = "  SELECT     OutGoingMailServer,WebMasterEmail, EmailMasterLoginPassword, AdminEmail, WHId " +
                            " FROM         CompanyWebsitMaster left outer join CompanyMaster on CompanyWebsitMaster.CompanyId=CompanyMaster.CompanyId WHERE     (WHId = " + Convert.ToInt32(ddlbusiness.SelectedValue) + ") and CompanyMaster.Compid='" + Session["Comid"] + "' ";
            SqlCommand     cmdma = new SqlCommand(strmal, con);
            SqlDataAdapter adpma = new SqlDataAdapter(cmdma);
            DataTable      dtma  = new DataTable();
            adpma.Fill(dtma);
            if (dtma.Rows.Count > 0)
            {
                string AdminEmail = dtma.Rows[0]["WebMasterEmail"].ToString();         // TextAdminEmail.Text;
                //string AdminEmail = txtusmail.Text;
                String Password = dtma.Rows[0]["EmailMasterLoginPassword"].ToString(); // TextEmailMasterLoginPassword.Text;

                //string body = "Test Mail Server - TestIwebshop";
                MailAddress to   = new MailAddress(ds.Rows[0]["EmailID"].ToString());
                MailAddress from = new MailAddress(AdminEmail);

                MailMessage objEmail = new MailMessage(from, to);
                objEmail.Subject = ddldoc.SelectedItem.Text;

                // if (RadioButtonList1.SelectedValue == "0")
                {
                    objEmail.Body       = body.ToString();
                    objEmail.IsBodyHtml = true;
                }


                objEmail.Priority = MailPriority.High;

                SmtpClient client = new SmtpClient();

                client.Credentials = new NetworkCredential(AdminEmail, Password);
                client.Host        = dtma.Rows[0]["OutGoingMailServer"].ToString();

                client.Send(objEmail);
            }
            else
            {
            }
        }
        catch (Exception tr)
        {
            //lblmsg.Visible = true;
            //lblmsg.Text = i + " Mail Sent - Error " + tr.Message;
        }
    }
コード例 #37
0
 public void MandarCorreo(MailMessage mensaje)
 {
     server.Send(mensaje);
 }
コード例 #38
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        public void SendEmail(EmailAccount emailAccount, string subject, string body,
                              string fromAddress, string fromName, string toAddress, string toName,
                              string replyTo            = null, string replyToName = null,
                              IEnumerable <string> bcc  = null, IEnumerable <string> cc   = null,
                              string attachmentFilePath = null, string attachmentFileName = null)
        {
            var message = new MailMessage();

            //from, to, reply to
            message.From = new MailAddress(fromAddress, fromName);
            message.To.Add(new MailAddress(toAddress, toName));
            if (!String.IsNullOrEmpty(replyTo))
            {
                message.ReplyToList.Add(new MailAddress(replyTo, replyToName));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(address.Trim());
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.CC.Add(address.Trim());
                }
            }

            //content
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = true;

            //create  the file attachment for this e-mail message
            if (!String.IsNullOrEmpty(attachmentFilePath) &&
                File.Exists(attachmentFilePath))
            {
                var attachment = new Attachment(attachmentFilePath);
                attachment.ContentDisposition.CreationDate     = File.GetCreationTime(attachmentFilePath);
                attachment.ContentDisposition.ModificationDate = File.GetLastWriteTime(attachmentFilePath);
                attachment.ContentDisposition.ReadDate         = File.GetLastAccessTime(attachmentFilePath);
                if (!String.IsNullOrEmpty(attachmentFileName))
                {
                    attachment.Name = attachmentFileName;
                }
                message.Attachments.Add(attachment);
            }

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host      = emailAccount.Host;
                smtpClient.Port      = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                {
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);
                }
                smtpClient.Send(message);
            }
        }
コード例 #39
0
ファイル: MailService.cs プロジェクト: lemadalin/FirmManager
        public void SendMail(Order order, Customer customer, string code)
        {
            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress("*****@*****.**");
            mailMessage.To.Add(customer.Email);
            mailMessage.Subject = "Furniture Express - Order number #" + order.OrderNumber;

            switch (code)
            {
            case "Production":
                mailMessage.Body = "ORDER IN PRODUCTION\r\n\r\n" +
                                   "Dear " + customer.FullName + ",\r\n" +
                                   "We want to let you know that your order #" + order.OrderNumber + ", processed on " + order.OrderDate.ToString() + ", is now in production.\r\n" +
                                   "You can find more details about your order below.\r\n" +
                                   "Thank you for choosing us!\r\n\r\n" +
                                   "Shipping address: " + customer.Street + " " + customer.City + " " + customer.State + " " + customer.Country + "\r\n" +
                                   "Items: ";
                foreach (var item in order.OrderItems)
                {
                    mailMessage.Body += item.Product.Title + " - Quantity: " + item.Quantity + "\r\n";
                }
                mailMessage.Body += "Total: $" + order.Total;
                break;

            case "Shipped":
                mailMessage.Body = "ORDER SHIPPED\r\n\r\n" +
                                   "Dear " + customer.FullName + ",\r\n" +
                                   "We want to let you know that your order #" + order.OrderNumber + ", processed on " + order.OrderDate.ToString() + ", has been shipped.\r\n" +
                                   "You can find more details about your order below.\r\n" +
                                   "Thank you for choosing us!\r\n\r\n" +
                                   "Shipping address: " + customer.Street + " " + customer.City + " " + customer.State + " " + customer.Country + "\r\n" +
                                   "Items: ";
                foreach (var item in order.OrderItems)
                {
                    mailMessage.Body += item.Product.Title + " - Quantity: " + item.Quantity + "\r\n";
                }
                mailMessage.Body += "Total: $" + order.Total;
                break;

            case "Canceled":
                mailMessage.Body = "ORDER CANCELED\r\n\r\n" +
                                   "Dear " + customer.FullName + ",\r\n" +
                                   "We want to let you know that your order #" + order.OrderNumber + ", processed on " + order.OrderDate.ToString() + ", has been canceled.\r\n" +
                                   "If you think that there has been a mistake, please contact us.\r\n" +
                                   "Thank you for choosing us!";
                mailMessage.Body += "Total: $" + order.Total;
                break;
            }

            mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            using (SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
            {
                smtpClient.EnableSsl             = true;
                smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;

                // Password got hidden for obvious reasons
                smtpClient.Credentials = new NetworkCredential("furniture.express12", "*****");

                smtpClient.Send(mailMessage.From.ToString(), mailMessage.To.ToString(), mailMessage.Subject, mailMessage.Body);
            }
        }
コード例 #40
0
        protected override void ExecuteProcedure(Imi.Framework.Job.JobArgumentCollection args)
        {
            if (!CheckParameters())
            {
                return;
            }

            // Find msg
            ArrayList transList = FindMessagesToSend();

            foreach (MailBoxMessage m in transList)
            {
                Tracing.TraceEvent(TraceEventType.Verbose, 0, String.Format(" found MailId {0}", m.MailId));

                string error = "";

                try
                {
                    AppMailMessage aMsg = new AppMailMessage(args["ReturnAddress"] as string, m.XmlMessageBody);

                    try
                    {
                        using (MailMessage eMail = new MailMessage())
                        {
                            if (args["FromAddress"] == null)
                            {
                                eMail.From = new MailAddress(args["Job"] as string);
                            }
                            else
                            {
                                eMail.From = new MailAddress(args["FromAddress"] as string, args["Job"] as string);
                            }

                            foreach (string address in aMsg.ToList)
                            {
                                eMail.To.Add(new MailAddress(address));
                            }


                            eMail.Subject = aMsg.Subject;
                            eMail.Body    = aMsg.MessageBody;

                            SmtpClient sc = new SmtpClient(args["MailServer"] as string);

                            if (args.ContainsKey("MailServerPort"))
                            {
                                if ((args["MailServerPort"] != null) && (!args["MailServerPort"].Equals("")))
                                {
                                    sc.Port = Convert.ToInt32(args["MailServerPort"] as string);
                                }
                            }

                            if ((args.ContainsKey("MailServerUser")) && (args.ContainsKey("MailServerPassword")))
                            {
                                if (((args["MailServerUser"] != null) && (!args["MailServerUser"].Equals(""))) && ((args["MailServerPassword"] != null) && (!args["MailServerPassword"].Equals(""))))
                                {
                                    sc.UseDefaultCredentials = false;

                                    sc.Credentials = new System.Net.NetworkCredential(args["MailServerUser"] as string, args["MailServerPassword"] as string);
                                }
                                else
                                {
                                    sc.UseDefaultCredentials = true;
                                }
                            }
                            else
                            {
                                sc.UseDefaultCredentials = true;
                            }

                            sc.Send(eMail);
                        }
                    }
                    catch (FormatException fe)
                    {
                        error = String.Format("Problems sending the email due to faulty email address list {0}. {1} {2}\n{3}",
                                              aMsg.ToList,
                                              fe.GetType().Name,
                                              fe.Message,
                                              fe.StackTrace);

                        Tracing.TraceEvent(TraceEventType.Error, 0, error);
                    }
                    catch (SmtpException e)
                    {
                        error = String.Format("Problems sending the email. {0} {1}\n{2}",
                                              e.GetType().Name,
                                              e.Message,
                                              e.StackTrace);

                        Tracing.TraceEvent(TraceEventType.Error, 0, error);
                    }
                }
                catch (ConfigurationErrorsException e)
                {
                    error = String.Format("Problems decoding email. {0} {1}\n{2}",
                                          e.GetType().Name,
                                          e.Message,
                                          e.StackTrace);

                    Tracing.TraceEvent(TraceEventType.Error, 0, error);
                }

                // -------------------------------------------
                // --- Update MAILBOX record
                // -------------------------------------------
                string ALMID_W = "";
                StartTransaction();

                if (error == "")
                {
                    dbMailAgent.ModifySend(m.MailId, ref ALMID_W);
                }
                else
                {
                    dbMailAgent.ModifyError(m.MailId, error, ref ALMID_W);
                }

                Commit();

                #region TracingOfResult
                if (error != "")
                {
                    Tracing.TraceEvent(TraceEventType.Error, 0,
                                       String.Format("MAILID {0} error while sending.\n{1}.", m.MailId, error));
                }
                else
                {
                    Tracing.TraceEvent(TraceEventType.Verbose, 0,
                                       String.Format("MAILID {0} was sent successfully.", m.MailId));
                }

                if (ALMID_W != "")
                {
                    Tracing.TraceEvent(TraceEventType.Error, 0,
                                       String.Format("Error {0} when updating MAILBOX record status.", ALMID_W));
                }
                #endregion
            }  // foreach ( MailMessage t in transList )
        }
コード例 #41
0
        public bool EnviarEmail()
        {
            var NombreVar   = NombreTextBox.Text;
            var Depatamento = DepartamentoTextBox.Text;
            var respuesta1  = Respuesta1RadioButtonList.Text;
            var respuesta2  = Respuesta2RadioButtonList.Text;
            var respuesta3  = Respuesta3RadioButtonList.Text;


            var fecha = DateTime.Now;


            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            //System.Net.MailMessage msg = new MailMessage();

            // msg.To.Add("*****@*****.**");

            msg.To.Add("*****@*****.**");

            msg.From = new MailAddress("*****@*****.**", "Sistamas Agentia", System.Text.Encoding.UTF8);

            msg.Subject = "Resultado de Cuestionario calidad de servicio Sistemas ";

            msg.SubjectEncoding = System.Text.Encoding.UTF8;

            msg.Body = "Saludos  RH\n\n Nombre de Colaborador:" + NombreVar +
                       "\n Del de partamento de :" + Depatamento +
                       "\n ¿Como califica la capcidad de respuesta en la que el tecnico le ha brindado solucion a sus incidencias?" + respuesta1 +
                       "\n ¿Le soluciono el o los problemas el tecnico que atendio su solicitud?" + respuesta2 +
                       "\n  ¿El tiempo de respuesta del tecnico a su solicitud?" + respuesta3 +
                       "\n En la fecha:" + fecha;

            msg.BodyEncoding = System.Text.Encoding.UTF8;

            msg.IsBodyHtml = false; //Si vas a enviar un correo con contenido html entonces cambia el valor a true
                                    //Aquí es donde se hace lo especial


            SmtpClient client = new SmtpClient();

            client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "diorelyon19");

            client.Port = 587;

            client.Host = "smtp.gmail.com"; //Este es el smtp valido para Gmail

            client.EnableSsl = true;        //Esto es para que vaya a través de SSL que es obligatorio con GMail

            try

            {
                client.Send(msg);

                return(true);
            }

            catch (ArgumentException e)

            {
                return(false);
            }
        }
コード例 #42
0
        private void SaveFeedbackBtn_Click(object sender, EventArgs e)
        {
            if (PositionList.SelectedIndex == -1)
            {
                MessageBox.Show("Select a position", "Missing attributes!");
                return;
            }

            if (ApplicantList.SelectedIndex == -1)
            {
                MessageBox.Show("Select an applicant", "Missing attributes!");
                return;
            }

            if (_currentFeed.Header == null)
            {
                MessageBox.Show("Please select the header before proceeding", "Missing component!");
                return;
            }

            if (_currentFeed.Sections.Count <= 0)
            {
                MessageBox.Show("Please select the sections before proceeding", "Missing component!");
                return;
            }

            _currentFeed.ReviewerId = Reviewer.Id.ToString();

            //check if there are null values in the header
            foreach (HeaderItem item in _currentFeed.Header.HeaderItems)
            {
                Control control = Controls.Find("header" + item.Id, true)[0];

                try
                {
                    switch (control.GetType().Name)
                    {
                    case "TextBox":
                    case "Label":
                        item.ValueChosen = ((TextBox)control).Text;
                        break;

                    case "ComboBox":
                        item.ValueChosen = ((ComboBox)control).SelectedItem.ToString();
                        break;

                    case "DateTimePicker":
                        item.ValueChosen = ((DateTimePicker)control).Value.ToString("dd/MM/yyyy");
                        break;
                    }

                    if (item.ValueChosen.Length <= 0)
                    {
                        throw new NullReferenceException();
                    }
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Please complete the header before proceeding", "Missing attributes!");
                    return;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error!");
                    return;
                }
            }

            bool sectionChecked = false;

            //check if there is null values in the sections
            foreach (Section s in _currentFeed.Sections)
            {
                RichTextBox text    = (RichTextBox)Controls.Find("comment" + s.SectionId, true)[0];
                ComboBox    codes   = (ComboBox)Controls.Find("codes" + s.SectionId, true)[0];
                CheckBox    checker = (CheckBox)Controls.Find("checker" + s.SectionId, true)[0];


                if (codes.SelectedIndex == -1)
                {
                    MessageBox.Show("Please complete the sections before proceeding -> Codes", "Missing attributes!");
                    return;
                }

                //Assign values to section object
                s.Comment    = text.Text;
                s.CodeChosen = codes.SelectedItem.ToString();
                s.IsChecked  = checker.Checked;

                if (s.Comment.Length <= 0)
                {
                    MessageBox.Show("Please complete the sections before proceeding -> Comment", "Missing attributes!");
                    return;
                }

                if (s.IsChecked)
                {
                    sectionChecked = true;
                }
            }

            if (!sectionChecked)
            {
                MessageBox.Show("Please check at least one section!", "Missing attributes!");
                return;
            }

            //end of field checkers

            MySql sql = new MySql();

            sql.OpenConnection();
            try
            {
                //update or insert the feedback
                if (String.IsNullOrEmpty(_currentFeed.FeedbackID))
                {
                    if (sql.SaveFeedback(_currentFeed))
                    {
                        MessageBox.Show("Feedback successfully saved.");
                    }
                }
                else
                {
                    if (sql.UpdateFeedback(_currentFeed))
                    {
                        MessageBox.Show("Feedback successfully updated.");
                    }
                }

                //checks whether is all the applications for the position is completed

                if (CheckPositionIsCompleted()) //means all of the applications have generated the feedback
                {
                    var result = MessageBox.Show("All the feedbacks for this current position: " + _currentFeed.Position._positionName + " is completed. \n Please choose the file name of the attachehment to be send to the applicants. \n Yes for Applicant name or No for Applicant code"
                                                 , "Select file name", MessageBoxButtons.YesNo);

                    //true for name false for code
                    bool filename = (result == DialogResult.Yes ? true : false);

                    try
                    {
                        int count = 0;

                        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");


                        foreach (Applicant app in sql.GetEmailList(_currentFeed.Position._positionId))
                        {
                            string      currentFilename = (filename ? app.Name : app.Id);
                            MailMessage mail            = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress(app.Email));
                            mail.Subject = "Application feedback for " + _currentFeed.Position._positionName + " in HappyTech.";
                            mail.Body    = "Hi " + app.Name + ",\nPlease find the attached file as the feedback from us regarding your application at HappyTech. \n\nRegards,\nHappy Tech HR";

                            System.Net.Mail.Attachment attachment;
                            attachment = new System.Net.Mail.Attachment(TempFileHandler.MakeTempFilePdf(app.Pdf, currentFilename));
                            mail.Attachments.Add(attachment);

                            SmtpServer.Port                  = 587;
                            SmtpServer.DeliveryMethod        = SmtpDeliveryMethod.Network;
                            SmtpServer.UseDefaultCredentials = false;
                            SmtpServer.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "happytech123");
                            SmtpServer.EnableSsl             = true;

                            SmtpServer.Send(mail);
                            count++;
                        }
                        MessageBox.Show("Total of " + count + " emails are sent.");
                    } catch (Exception exc)
                    {
                        throw exc;
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString(), "Ops! Error occured!");
            }
            finally
            {
                sql.CloseConnection();
            }
        }
コード例 #43
0
        // send the email
        private void Send()
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress("Keno San Pablo", "*****@*****.**"));

            // parse to addresses
            if (!string.IsNullOrEmpty(toField))
            {
                string[] toAddresses = toField.Split(',');
                foreach (var address in toAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.To.Add(new MailboxAddress(name, addr));
                }
            }
            // parse cc addresses
            if (!string.IsNullOrEmpty(ccField))
            {
                string[] ccAddresses = ccField.Split(',');
                foreach (var address in ccAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.Cc.Add(new MailboxAddress(name, addr));
                }
            }

            // parse bcc addresses
            if (!string.IsNullOrEmpty(bccField))
            {
                string[] bccAddresses = bccField.Split(',');
                foreach (var address in bccAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.Bcc.Add(new MailboxAddress(name, addr));
                }
            }

            message.Subject = subjectField;

            BodyBuilder builder = new BodyBuilder();

            builder.TextBody = bodyField;
            if (!string.IsNullOrEmpty(attachField))
            {
                try
                {
                    builder.Attachments.Add(attachField);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            message.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("ece433tester", "thisclassman");

                try
                {
                    client.Send(message);
                    // Configure the message box to be displayed
                    string           messageBoxText = "Message Sent!";
                    string           caption        = "Success";
                    MessageBoxButton button         = MessageBoxButton.OK;
                    MessageBoxImage  icon           = MessageBoxImage.Exclamation;
                    MessageBox.Show(messageBoxText, caption, button, icon);
                    CloseAction();
                }
                catch (Exception)
                {
                    throw;
                }
                client.Disconnect(true);
            }
        }
コード例 #44
0
ファイル: Form1.cs プロジェクト: jokerfvd/Naoprivatiza
        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            if (textBox1.Text == ""){
                MessageBox.Show("Digite o seu nome!");
                textBox1.Focus();
                return;
            }
            if (textBox2.Text == ""){
                MessageBox.Show("Digite o seu email!");
                textBox2.Focus();
                return;
            }
            if (textBox3.Text == ""){
                MessageBox.Show("Digite a sua senha!");
                textBox3.Focus();
                return;
            }
            if (!validaEmail())
            {
                MessageBox.Show("O email digitado é inválido!");
                textBox2.Focus();
                return;
            }
            if (!setSmttp())
            {
                MessageBox.Show("Nao consigo enviar por esse remetente, favor escolher um email do gmail!");
                textBox2.Focus();
                return;
            }

            //preprando para enviar o email
            MailAddress from = new MailAddress(textBox2.Text, textBox1.Text);
            //var to = new MailAddress();
            MailMessage message = new MailMessage();
            message.From = from;
            message.Body = richTextBox1.Text+textBox1.Text;//email com o nome
            message.Subject = comboBox1.Text;
            message.BodyEncoding = UTF8Encoding.UTF8;
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            SmtpClient client = new SmtpClient();
            client.Host = smtpHost;
            client.Port = smtpPort;
            client.EnableSsl = smtpSsl;
            client.Timeout = 40000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(textBox2.Text,textBox3.Text);

            //client.Credentials = CredentialCache.DefaultCredentials; //para o servidor preencher

            bool first = true;
            label6.Visible = true;
            label6.Update();
            int count = 0;
            try{
                foreach (String lista in emails)
                {
                    count++;
                    label6.Text = String.Format("Enviando email para os deputados ({0}/{1})", count, emails.Count);
                    label6.Update();
                    if (first)
                        first = false;
                    else //esperando 5s para enviar o proximo pois pode dar algum erro enviando muitos de uma vez.
                        System.Threading.Thread.Sleep(5000);
                    foreach(String email in lista.Split(';'))
                        message.Bcc.Add(new MailAddress(email));
                    client.Send(message);
                    for (int i = message.Bcc.Count - 1; i >= 0;i-- )
                        message.Bcc.RemoveAt(i);
                    progressBar1.PerformStep();
                }
                label6.Visible = false;
            }
            catch (Exception ex){
                MessageBox.Show("Houve um problema! =( : "+ex.ToString());
            }

        }
コード例 #45
0
        public ApiResponse <LoginModel> RegistrationUser(LoginModel model)
        {
            ApiResponse <LoginModel> response = new ApiResponse <LoginModel>();
            var userDetail = uow.Repository <LoginModel>().SQLQuery("EXEC spRegisterUser @firstname,@lastname,@email,@password,@gender",
                                                                    new object[]
            {
                new SqlParameter("@firstname", model.FirstName),
                new SqlParameter("@lastname", model.LastName),
                new SqlParameter("@email", model.EmailAddress),
                new SqlParameter("@password", Security.Encrypt(model.Password)),
                new SqlParameter("@gender", model.GenderType)
            }
                                                                    ).FirstOrDefault();

            if (userDetail != null)
            {
                response.Success = true;
                response.Data.Add(userDetail);

                if (userDetail.UserId > 0)
                {
                    System.Net.Mail.MailMessage mailMesg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["FromMail"], model.EmailAddress);
                    mailMesg.Subject = "Welcome to Stay Healthy World Community";

                    string body = string.Empty;
                    //using streamreader for reading my htmltemplate

                    using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/RegistrationEmail.html")))
                    {
                        body = reader.ReadToEnd();
                    }

                    body = body.Replace("[Fname]", model.FirstName); //replacing the required things

                    body = body.Replace("[Lname]", model.LastName);

                    //body = body.Replace("{message}", message);


                    mailMesg.Body       = body;
                    mailMesg.IsBodyHtml = true;

                    var objSMTP = new SmtpClient
                    {
                        Host                  = System.Configuration.ConfigurationManager.AppSettings["Host"],
                        Port                  = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]),
                        EnableSsl             = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]),
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["FromMail"], System.Configuration.ConfigurationManager.AppSettings["Password"])
                    };

                    try
                    {
                        objSMTP.Send(mailMesg);
                    }
                    catch (Exception ex)
                    {
                        mailMesg.Dispose();
                        mailMesg = null;
                    }
                }
            }
            return(response);
        }
コード例 #46
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //create the mail message
                var message = new MailMessage();
                var mail    = message;

                //set the addresses
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                //mail.To.Add("*****@*****.**");
                mail.IsBodyHtml = true;

                //set the content
                mail.Subject = "New Title Order request from ";
                mail.Body    = "<table style='width: 400px;'  border='0' cellpadding='0' cellspacing='0'>" +
                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px; color: Red;'>" +
                               "Contact Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Ordered By:</td>" +
                               "<td>" +
                               ddlOrderedBy.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company Name:</td>" +
                               "<td>" +
                               txtCompanyName.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company Address:</td>" +
                               "<td>" +
                               txtCompanyAddress.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company City:</td>" +
                               "<td>" +
                               txtCompanyCity.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company State:</td>" +
                               "<td>" +
                               ddlCompanyState.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company Zip:</td>" +
                               "<td>" +
                               txtCompanyZip.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Email:</td>" +
                               "<td>" +
                               txtEmail.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Contact Telephone:</td>" +
                               "<td>" +
                               txtContactTelephone.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Company Fax:</td>" +
                               "<td>" +
                               txtContactFax.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Loan Officer & Processor Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Loan Officer:</td>" +
                               "<td>" +
                               txtLoanOfficer.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Loan Processor:</td>" +
                               "<td>" +
                               txtLoanProcessor.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Transaction Type:</td>" +
                               "<td>" +
                               ddlTransactionType.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Loan Amount:</td>" +
                               "<td>" +
                               txtLoanAmount.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Purchase Amount:</td>" +
                               "<td>" +
                               txtPurchaseAmount.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Borrower/Buyer Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Borrower:</td>" +
                               "<td>" +
                               txtBorrower.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Borrower SSN#:</td>" +
                               "<td>" +
                               txtBuyerSSN.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Home Telephone:</td>" +
                               "<td>" +
                               txtHomeTelephone.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Work Telephone:</td>" +
                               "<td>" +
                               txtWorkTelephone.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Address:</td>" +
                               "<td>" +
                               txtBorrowerAddress.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "City:</td>" +
                               "<td>" +
                               txtBorrowerCIty.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "State:</td>" +
                               "<td>" +
                               ddlBorrowerState.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Zip:</td>" +
                               "<td>" +
                               txtBorrowerZip.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Co-Borrower:</td>" +
                               "<td>" +
                               txtCoBorrower.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "SSN#:</td>" +
                               "<td>" +
                               txtCoBorrowerSSN.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Seller Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Seller:</td>" +
                               "<td>" +
                               txtSeller.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "SSN#:</td>" +
                               "<td>" +
                               txtSellerSSN.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Home Telephone:</td>" +
                               "<td>" +
                               txtSellerHomeTel.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Work Telephone:</td>" +
                               "<td>" +
                               txtSellerWorkTel.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Address:</td>" +
                               "<td>" +
                               txtSellerAddress.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "City:</td>" +
                               "<td>" +
                               txtSellerCity.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "State:</td>" +
                               "<td>" +
                               ddlSellerState.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Zip:</td>" +
                               "<td>" +
                               txtSellerZip.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Co-Seller:</td>" +
                               "<td>" +
                               txtCoSeller.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "SSN#:</td>" +
                               "<td>" +
                               txtCoSellerSSN.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Property Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +


                               PropertyAddressCheck() +


                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Who Orders Payoff:</td>" +
                               "<td>" +
                               ddlWhoOrdersPayoff.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "How Many Payoffs:</td>" +
                               "<td>" +
                               ddlHowManyPayoffs.SelectedValue +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Name of Bank Being Paid Off:</td>" +
                               "<td>" +
                               txtBankName.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Account Number:</td>" +
                               "<td>" +
                               txtAccountNumber.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Sale Price (if purchased):</td>" +
                               "<td>" +
                               txtSalePrice.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Loan Amount:</td>" +
                               "<td>" +
                               txtPropertyLoanAmount.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Special Instructions:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Instructions:</td>" +
                               "<td>" +
                               txtSpecialInstructions.Text +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 450px; color: Red;'>" +
                               "Payoff Information:</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "&nbsp;</td>" +
                               "<td>" +
                               "&nbsp;" +
                               "</td>" +
                               "</tr>" +

                               "<tr>" +
                               "<td style='font-weight:bold; width: 130px;'>" +
                               "Information:</td>" +
                               "<td>" +
                               txtPayoffInformation.Text +
                               "</td>" +
                               "</tr>" +

                               "</table>";

                //send the message
                var smtp = new SmtpClient("relay-hosting.secureserver.net");
                smtp.Send(mail);

                //create a status message
                lblOrderStatus.Text = "Email Sent, Someone will be contacting you promptly";
                orderstatus.Visible = true;
                order.Visible       = false;
            }
            catch (Exception ex)
            {
                lblOrderStatus.Text = "";
                lblOrderStatus.Text = ex.Message;
                orderstatus.Visible = true;
                order.Visible       = false;
            }
        }
コード例 #47
0
        public bool Send_SMTP()
        {
            try
            {
                if (string.IsNullOrEmpty(MailFrom))
                {
                    Event = "Failed: Please provide FROM email address.";
                    return(false);
                }
                if (string.IsNullOrEmpty(MailTo))
                {
                    Event = "Failed: Please provide TO email address.";
                    return(false);
                }
                if (string.IsNullOrEmpty(Subject))
                {
                    Event = "Failed: Please provide email subject.";
                    return(false);
                }

                if (string.IsNullOrEmpty(SMTPMailHost))
                {
                    Event = "Failed: Please provide Mail Host";
                    return(false);
                }
                mVE.Value = MailFrom;
                var fromAddress = new MailAddress(mVE.ValueCalculated, "_Amdocs Ginger Automation");

                mVE.Value = SMTPMailHost;
                string mailHost = mVE.ValueCalculated;

                if (this.SMTPPort == 0 || this.SMTPPort == null)
                {
                    this.SMTPPort = 25;
                }
                var smtp = new SmtpClient()
                {
                    Host                  = mailHost, // amdocs config
                    Port                  = (int)this.SMTPPort,
                    EnableSsl             = EnableSSL,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = !ConfigureCredential
                };

                if (ConfigureCredential)
                {
                    bool checkValueDecrypt;
                    checkValueDecrypt = true;
                    string DecryptPass = EncryptionHandler.DecryptString(SMTPPass, ref checkValueDecrypt);
                    if (checkValueDecrypt)
                    {
                        smtp.Credentials = new NetworkCredential(SMTPUser, DecryptPass);
                    }
                    else
                    {
                        smtp.Credentials = new NetworkCredential(SMTPUser, SMTPPass);
                    }
                }
                mVE.Value = MailTo;
                string emails    = mVE.ValueCalculated;
                Array  arrEmails = emails.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage();
                foreach (string email in arrEmails)
                {
                    myMail.To.Add(email);
                }

                //Add CC
                if (!String.IsNullOrEmpty(MailCC))
                {
                    Array arrCCEmails = MailCC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string MailCC1 in arrCCEmails) //arrEmails) // Updated by Preeti for defect 2464
                    {
                        myMail.CC.Add(MailCC1);
                    }
                }

                mVE.Value = Subject;
                string subject = mVE.ValueCalculated;

                mVE.Value = Body;
                string body = mVE.ValueCalculated;

                myMail.From       = fromAddress;
                myMail.IsBodyHtml = IsBodyHTML;

                myMail.Subject = subject.Replace('\r', ' ').Replace('\n', ' ');
                myMail.Body    = body;

                foreach (string AttachmentFileName in Attachments)
                {
                    if (String.IsNullOrEmpty(AttachmentFileName) == false)
                    {
                        Attachment a = new Attachment(AttachmentFileName);
                        myMail.Attachments.Add(a);
                    }
                }
                if (alternateView != null)
                {
                    myMail.AlternateViews.Add(alternateView);
                }
                smtp.Send(myMail);

                return(true);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Mailbox unavailable"))
                {
                    Event = "Failed: Please provide correct FROM email address";
                }
                else if (ex.StackTrace.Contains("System.Runtime.InteropServices.Marshal.GetActiveObject"))
                {
                    Event = "Please make sure ginger/outlook opened in same security context (Run as administrator or normal user)";
                }
                else if (ex.StackTrace.Contains("System.Security.Authentication.AuthenticationException") || ex.StackTrace.Contains("System.Net.Sockets.SocketException"))
                {
                    Event = "Please check SSL configuration";
                }
                else
                {
                    Event = "Failed: " + ex.Message;
                }
                return(false);
            }
        }
コード例 #48
0
        private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority,
                                               MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable <Attachment> attachments,
                                               string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL)
        {
            string retValue = string.Empty;

            mailMessage.Priority   = (System.Net.Mail.MailPriority)priority;
            mailMessage.IsBodyHtml = (bodyFormat == MailFormat.Html);


            // Only modify senderAdress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpAuthentication == "1" || smtpAuthentication == "2")
            {
                //if the senderAddress is the email address of the Host then switch it smtpUsername if different
                //if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailMessage.Sender.Address;
                    var senderDisplayName = mailMessage.Sender.DisplayName;
                    var needUpdateSender  = false;
                    if (smtpUsername.Contains("@") && senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpUsername, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpUsername;
                        needUpdateSender = true;
                    }
                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }
                    if (needUpdateSender)
                    {
                        mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName);
                    }
                }
                else if (smtpUsername.Contains("@"))
                {
                    mailMessage.Sender = new MailAddress(smtpUsername, Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle);
                }
            }

            //attachments
            foreach (var attachment in attachments)
            {
                mailMessage.Attachments.Add(attachment);
            }

            //message
            mailMessage.SubjectEncoding = bodyEncoding;
            mailMessage.Subject         = HtmlUtils.StripWhiteSpace(subject, true);
            mailMessage.BodyEncoding    = bodyEncoding;

            AddAlternateView(mailMessage, body, bodyEncoding);

            smtpServer = smtpServer.Trim();
            if (SmtpServerRegex.IsMatch(smtpServer))
            {
                try
                {
                    //to workaround problem in 4.0 need to specify host name
                    using (var smtpClient = new SmtpClient())
                    {
                        var smtpHostParts = smtpServer.Split(':');
                        smtpClient.Host = smtpHostParts[0];
                        if (smtpHostParts.Length > 1)
                        {
                            // port is guaranteed to be of max 5 digits numeric by the RegEx check
                            var port = Convert.ToInt32(smtpHostParts[1]);
                            if (port < 1 || port > 65535)
                            {
                                return(Localize.GetString("SmtpInvalidPort"));
                            }

                            smtpClient.Port = port;
                        }
                        // else the port defaults to 25 by .NET when not set

                        smtpClient.ServicePoint.MaxIdleTime     = Host.SMTPMaxIdleTime;
                        smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit;

                        switch (smtpAuthentication)
                        {
                        case "":
                        case "0":     //anonymous
                            break;

                        case "1":     //basic
                            if (!String.IsNullOrEmpty(smtpUsername) && !String.IsNullOrEmpty(smtpPassword))
                            {
                                smtpClient.UseDefaultCredentials = false;
                                smtpClient.Credentials           = new NetworkCredential(smtpUsername, smtpPassword);
                            }
                            break;

                        case "2":     //NTLM
                            smtpClient.UseDefaultCredentials = true;
                            break;
                        }
                        smtpClient.EnableSsl = smtpEnableSSL;
                        smtpClient.Send(mailMessage);
                        smtpClient.Dispose();
                    }
                }
                catch (Exception exc)
                {
                    var exc2 = exc as SmtpFailedRecipientException;
                    if (exc2 != null)
                    {
                        retValue = string.Format(Localize.GetString("FailedRecipient"), exc2.FailedRecipient) + " ";
                    }
                    else if (exc is SmtpException)
                    {
                        retValue = Localize.GetString("SMTPConfigurationProblem") + " ";
                    }

                    //mail configuration problem
                    if (exc.InnerException != null)
                    {
                        retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                        Exceptions.Exceptions.LogException(exc.InnerException);
                    }
                    else
                    {
                        retValue += exc.Message;
                        Exceptions.Exceptions.LogException(exc);
                    }
                }
                finally
                {
                    mailMessage.Dispose();
                }
            }
            else
            {
                retValue = Localize.GetString("SMTPConfigurationProblem");
            }

            return(retValue);
        }
コード例 #49
0
        /// <summary>
        /// 发送HTML格式邮件(UTF8)
        /// </summary>
        public static string MailTo(SmtpConfig config,
                                    MailAddress AddrFrom, MailAddress AddrTo,
                                    MailAddressCollection cc, MailAddressCollection bCC,
                                    string Subject, string BodyContent, bool isHtml, List <Attachment> attC)
        {
            MailMessage msg = new MailMessage(AddrFrom, AddrTo);

            #region 抄送
            if (cc != null && cc.Count > 0)
            {
                foreach (MailAddress cAddr in cc)
                {
                    msg.CC.Add(cAddr);
                }
            }
            #endregion

            #region 密送
            if (bCC != null && bCC.Count > 0)
            {
                foreach (MailAddress cAddr in bCC)
                {
                    msg.Bcc.Add(cAddr);
                }
            }
            #endregion

            #region 附件列表
            if (attC != null && attC.Count > 0)
            {
                foreach (Attachment item in attC)
                {
                    msg.Attachments.Add(item);
                }
            }
            #endregion

            msg.IsBodyHtml = isHtml;
            msg.Priority   = MailPriority.High;

            msg.Subject         = Subject;
            msg.SubjectEncoding = config.ContentEncoding;
            msg.BodyEncoding    = config.ContentEncoding;
            msg.Body            = BodyContent;

            SmtpClient client = new SmtpClient(config.SmtpServer, config.Port);
            if (config.Credentials != null)
            {
                client.Credentials = config.Credentials;
            }
            client.EnableSsl = config.SSLConnect;

            try
            {
                client.Send(msg);
                return("0");
            }
            catch (Exception exp)
            {
                return(exp.Message);
            }
        }
コード例 #50
0
    public static Boolean SendMail(
        String _SenderMail        = null,
        String _SenderName        = null,
        String _RecipientToMails  = null,
        String _RecipientCCMails  = null,
        String _RecipientBCCMails = null,
        String _Subject           = null,
        String _BodyMessage       = null,
        Boolean _IsBodyHtml       = true,

        List <ICalendar> _ICalendars = null,

        IDictionary <String, Byte[]> Attachments = null,

        String _MailHost   = null,
        Int32?_MailPort    = null,
        String _Username   = null,
        String _Password   = null,
        Int32?_TimeOut     = 100000,
        Boolean?_EnableSsl = true
        )
    {
        try
        {
            Char[] Delimiters = new Char[] { ';' };

            //contrôle de cohérence
            if ((String.IsNullOrEmpty(_MailHost)) || (_MailPort == null))
            {
                return(false);
            }

            //initialisation du serveur
            var _SmtpClient = new SmtpClient(_MailHost, Int32.Parse(_MailPort.ToString()));
            if (!String.IsNullOrEmpty(_Username) && !String.IsNullOrEmpty(_Password))
            {
                _SmtpClient.Credentials = new NetworkCredential(_Username, _Password);
            }
            ;
            _SmtpClient.EnableSsl = Boolean.Parse(_EnableSsl.ToString());
            _SmtpClient.Timeout   = Int32.Parse(_TimeOut.ToString());

            //initialisation du message
            MailMessage _MailMessage = new MailMessage();
            _MailMessage.Subject         = _Subject;
            _MailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            _MailMessage.Body            = _BodyMessage;
            _MailMessage.BodyEncoding    = System.Text.Encoding.UTF8;
            _MailMessage.IsBodyHtml      = _IsBodyHtml;
            _MailMessage.Priority        = MailPriority.Normal;

            //expéditeur
            _MailMessage.From = new MailAddress(_SenderMail, _SenderName);

            //destinataires
            String[] _Recipients = _RecipientToMails.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
            for (Int32 i = 0; i < _Recipients.Length; i++)
            {
                MailAddress CurrentMailAddress = new MailAddress(_Recipients[i].ToString().Trim());
                _MailMessage.To.Add(CurrentMailAddress);
            }
            //destinataires en copie carbone
            if (!String.IsNullOrEmpty(_RecipientCCMails))
            {
                String[] _RecipientCCs = _RecipientCCMails.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
                for (Int32 i = 0; i < _RecipientCCs.Length; i++)
                {
                    MailAddress CurrentMailAddress = new MailAddress((String)_RecipientCCs[i].ToString().Trim());
                    _MailMessage.CC.Add(CurrentMailAddress);
                }
            }
            //destinataires en copie carbone invisible
            if (!String.IsNullOrEmpty(_RecipientBCCMails))
            {
                String[] _RecipientBCCs = _RecipientBCCMails.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
                for (Int32 i = 0; i < _RecipientBCCs.Length; i++)
                {
                    MailAddress CurrentMailAddress = new MailAddress(_RecipientBCCs[i].ToString().Trim());
                    _MailMessage.Bcc.Add(CurrentMailAddress);
                }
            }


            //invitations
            if ((_ICalendars != null) && (_ICalendars.Count > 0))
            {
                List <String> _Calendars = ConvertICalendars(_ICalendars);

                Int32 _Index = 1;
                foreach (String _Current in _Calendars)
                {
                    var          _CurrentBytes = Encoding.UTF8.GetBytes(_Current);
                    MemoryStream _MemoryStream = new MemoryStream(_CurrentBytes);
                    Attachment   _Attachment   = new System.Net.Mail.Attachment(_MemoryStream, String.Format("Invitation{0}.ics", _Index), "text/calendar");
                    _MailMessage.Attachments.Add(_Attachment);
                    _Index++;
                }
            }

            //pièces jointes
            if (Attachments != null && Attachments.Count > 0)
            {
                foreach (KeyValuePair <String, Byte[]> Current in Attachments)
                {
                    String     Name       = (Current.Key != null ? Current.Key : "Fichier");
                    Stream     Stream     = new MemoryStream(Current.Value);
                    Attachment Attachment = new Attachment(Stream, Name);
                    _MailMessage.Attachments.Add(Attachment);
                }
            }

            _SmtpClient.Send(_MailMessage);
            _SmtpClient.Dispose();
        }
        catch (Exception Ex)
        {
            return(false);
        }
        return(true);
    }
        private void SendEmail(string mailAddress, string formatFile)
        {
            MailMessage objMailMessage = new MailMessage();
            SmtpClient objSmtpClient = null;
            String filePath = "";

            if (formatFile == "xls")
            {
                try
                {
                    filePath = Path.GetFullPath("Request.xls");
                    service.SaveRequestToXlsFile(service.GetElement(id.Value), filePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (formatFile == "doc")
            {
                try
                {
                    filePath = Path.GetFullPath("Request.doc");
                    service.SaveRequestToDocFile(service.GetElement(id.Value), filePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            try
            {
                objMailMessage.From = new MailAddress(ConfigurationManager.AppSettings["MailLogin"]);
                objMailMessage.To.Add(new MailAddress(mailAddress));
                objMailMessage.Subject = "Новая заявка на медикменты";
                objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
                objMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

                string file = Path.GetFullPath(filePath);
                Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);
                objMailMessage.Attachments.Add(attach);

                objSmtpClient = new SmtpClient("smtp.gmail.com", 587);
                objSmtpClient.UseDefaultCredentials = false;
                objSmtpClient.EnableSsl = true;
                objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                objSmtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["MailLogin"],
                    ConfigurationManager.AppSettings["MailPassword"]);

                objSmtpClient.Send(objMailMessage);
               // File.Delete(filePath);
                MessageBox.Show("Заявка отправлена", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Что-то пошло не так"+" "+ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
            }
            finally
            {
                objMailMessage = null;
                objSmtpClient = null;
            }
        }
コード例 #52
0
 public void Send(MailMessage message)
 {
     BeforeSend(this, EventArgs.Empty);
     PreprocessMessage(message);
     _client.Send(message);
 }
コード例 #53
0
        public void ProcessOrder(Cart cart, ShippingDetails shippingDetails)
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.EnableSsl             = emailSettings.UseSsl;
                smtpClient.Host                  = emailSettings.ServerName;
                smtpClient.Port                  = emailSettings.ServerPort;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials           = new NetworkCredential(emailSettings.Username, emailSettings.Password);

                if (emailSettings.WriteAsFile)
                {
                    smtpClient.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
                    smtpClient.EnableSsl = false;
                }

                StringBuilder msgBody = new StringBuilder()
                                        .AppendLine("A new Order has been submitted")
                                        .AppendLine("----------")
                                        .AppendLine("Books: ");

                foreach (var line in cart.CartLines)
                {
                    var subtotal = line.Book.Price * line.Quantity;
                    msgBody.AppendFormat("{0} x {1} (subtotal: {2:C})", line.Quantity, line.Book.Title, subtotal);
                }

                msgBody.AppendFormat("Total order value : {0:C}", cart.ComputerTotalValue())
                .AppendLine("----------")
                .AppendLine("Ship to :")
                .AppendLine(shippingDetails.Name)
                .AppendLine(shippingDetails.Line1)
                .AppendLine(shippingDetails.Line2)
                .AppendLine(shippingDetails.State)
                .AppendLine(shippingDetails.City)
                .AppendLine(shippingDetails.Country)
                .AppendLine("----------")
                .AppendFormat("Gift Wrap :{0} ", shippingDetails.GiftWrap ? "Yes" : "No");

                MailMessage mailMessage = new MailMessage(
                    emailSettings.MailFromAddress,
                    emailSettings.MailToAddress,
                    "New order submitted",
                    msgBody.ToString()
                    );

                if (emailSettings.WriteAsFile)
                {
                    mailMessage.BodyEncoding = Encoding.ASCII;
                }

                try
                {
                    smtpClient.Send(mailMessage);
                }
                catch (Exception e)
                {
                    Debug.Print(e.Message);
                }
            }
        }
コード例 #54
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <returns>发送是否成功</returns>
        public bool Send()
        {
            try
            {
                MailMessage msg = new MailMessage();
                msg.From    = new MailAddress(m_From);
                msg.Subject = m_Subject;
                //邮件正文
                msg.Body = m_Body;
                char[] ch = { ',' };
                if (!string.IsNullOrEmpty(m_To))
                {
                    string[] address = m_To.Split(ch, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < address.Length; i++)
                    {
                        MailAddress toAddress = new MailAddress(address[i]);
                        msg.To.Add(toAddress);
                    }
                }
                if (!string.IsNullOrEmpty(m_Cc))
                {
                    string[] addressCc = m_Cc.Split(ch, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < addressCc.Length; i++)
                    {
                        MailAddress toAddress = new MailAddress(addressCc[i]);
                        msg.CC.Add(toAddress);
                    }
                }
                if (!string.IsNullOrEmpty(m_Bcc))
                {
                    string[] addressBcc = m_Bcc.Split(ch, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < addressBcc.Length; i++)
                    {
                        MailAddress toAddress = new MailAddress(addressBcc[i]);
                        msg.Bcc.Add(toAddress);
                    }
                }
                //內容是否未HTML格式
                msg.IsBodyHtml = m_IsBodyHtml;

                //获取所有邮件附件
                char[]   cr   = { ';' };
                string[] file = m_File.Split(cr);
                for (int n = 0; n < file.Length; n++)
                {
                    if (file[n] != "")
                    {
                        //附件对象
                        Attachment data = new Attachment(file[n], MediaTypeNames.Application.Octet);
                        //附件资料
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.CreationDate     = System.IO.File.GetCreationTime(file[n]);
                        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file[n]);
                        disposition.ReadDate         = System.IO.File.GetLastAccessTime(file[n]);
                        //加入邮件附件
                        msg.Attachments.Add(data);
                    }
                }

                //使用简单邮件传输协议来传送邮件
                SmtpClient sendMail = new SmtpClient();
                //发送邮件的服务器名或地址
                sendMail.Host = m_Host;
                sendMail.Port = m_Port;
                //验证发件人的身份
                sendMail.Credentials = new NetworkCredential(m_UserName, m_Password);
                //处理待发送邮件的方法
                sendMail.DeliveryMethod = SmtpDeliveryMethod.Network;
                sendMail.EnableSsl      = m_Ssl;
                //发送邮件
                sendMail.Send(msg);

                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception("EMail发送失败" + ex);
            }
        }
コード例 #55
0
        public bool Send()
        {
            //使用指定的邮件地址初始化MailAddress实例
            MailAddress maddr = new MailAddress(mailFrom);
            //初始化MailMessage实例
            MailMessage myMail = new MailMessage();


            //向收件人地址集合添加邮件地址
            if (mailToArray != null)
            {
                for (int i = 0; i < mailToArray.Length; i++)
                {
                    myMail.To.Add(mailToArray[i].ToString());
                }
            }

            //向抄送收件人地址集合添加邮件地址
            if (mailCcArray != null)
            {
                for (int i = 0; i < mailCcArray.Length; i++)
                {
                    myMail.CC.Add(mailCcArray[i].ToString());
                }
            }
            //发件人地址
            myMail.From = maddr;

            //电子邮件的标题
            myMail.Subject = mailSubject;

            //电子邮件的主题内容使用的编码
            myMail.SubjectEncoding = Encoding.UTF8;

            //电子邮件正文
            myMail.Body = mailBody;

            //电子邮件正文的编码
            myMail.BodyEncoding = Encoding.Default;

            myMail.Priority = MailPriority.High;

            myMail.IsBodyHtml = isbodyHtml;

            //在有附件的情况下添加附件
            try
            {
                if (attachmentsPath != null && attachmentsPath.Length > 0)
                {
                    Attachment attachFile = null;
                    foreach (string path in attachmentsPath)
                    {
                        attachFile = new Attachment(path);
                        myMail.Attachments.Add(attachFile);
                    }
                }
            }
            catch (Exception err)
            {
                throw new Exception("在添加附件时有错误:" + err);
            }

            SmtpClient smtp = new SmtpClient();

            //指定发件人的邮件地址和密码以验证发件人身份
            smtp.Credentials = new System.Net.NetworkCredential(mailFrom, mailPwd);


            //设置SMTP邮件服务器
            smtp.Host = host;

            try
            {
                //将邮件发送到SMTP邮件服务器
                smtp.Send(myMail);
                return(true);
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                return(false);
            }
        }
コード例 #56
0
        public async Task <IActionResult> Register(AppUser appUser)
        {
            Message _Message = new Message();

            try
            {
                AppUser user = await userMgr.FindByEmailAsync(appUser.Email);

                if (user == null)
                {
                    user = new AppUser
                    {
                        UserName  = appUser.UserName,
                        Email     = appUser.Email,
                        FirstName = appUser.FirstName,
                        LastName  = appUser.LastName
                    };
                    IdentityResult result = await userMgr.CreateAsync(user, "Test123!");

                    if (result.Succeeded == true)
                    {
                        // string callbackUrl = "file://*****:*****@anblicks.com",
                            Subject     = subject
                        };
                        MailMessage msg = new MailMessage();
                        msg.From = new MailAddress("*****@*****.**");
                        msg.To.Add(new MailAddress(message.Destination));
                        msg.Subject    = message.Subject;
                        msg.Body       = message.Body;
                        msg.IsBodyHtml = true;
                        SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32(587))
                        {
                            UseDefaultCredentials = false
                        };
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "sriram@123");
                        smtpClient.Credentials = credentials;
                        smtpClient.EnableSsl   = true;
                        smtpClient.Send(msg);
                        smtpClient.Dispose();
                        _Message.Status        = "Success";
                        _Message.StatusCode    = 200;
                        _Message.StatusMessage = "User Successfully Created !!";
                    }
                    else
                    {
                        _Message.Status        = "Failure";
                        _Message.StatusCode    = 200;
                        _Message.StatusMessage = "User Already Existed !!";
                    }
                }
            }
            catch (Exception ex)
            {
                _Message.Status        = "Failure";
                _Message.StatusCode    = (int)HttpStatusCode.ExpectationFailed;
                _Message.StatusMessage = ex.Message;
            }
            return(Ok(_Message));
        }
コード例 #57
0
ファイル: Mailman.cs プロジェクト: jaywha/RApID
        public static bool SendEmail(string subject = "", string body = "", Exception exception = null)
        {
            ReportedExceptions.Add(exception);

            string sUserName = Environment.UserName;

            try
            {
                using (MailMessage _emailMessage = new MailMessage())
                {
                    StringBuilder recipientList = new StringBuilder();
                    recipientList.Append("[email protected],");
                    recipientList.Append("*****@*****.**");

                    _emailMessage.To.Add(recipientList.ToString());

                    #region assign who email is from
                    string emailQuery = "SELECT EmailAddress FROM UserLogin WHERE [Username] = '" + sUserName + "'";
                    string email      = sqlClass.SQLGet_String(emailQuery, csObjectHolder.csObjectHolder.ObjectHolderInstance().HummingBirdConnectionString);

                    if (string.IsNullOrEmpty(email))
                    {
                        throw new Exception("User (" + sUserName + ") does not have a valid email address or username in the UserLogin table.");
                    }

                    _emailMessage.From = new MailAddress(email);
                    #endregion

                    _emailMessage.IsBodyHtml = true;
                    if (exception != null)
                    {
                        _emailMessage.Priority = MailPriority.High;
                    }

                    _emailMessage.Subject = string.IsNullOrWhiteSpace(subject) ?
                                            $"RApID Exception - {Environment.MachineName} under {Environment.UserName}"
                    : subject;

#if DEBUG
                    var initialPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
#else
                    var initialPath = @"\\joi\eu\Public\EE Process Test\Software\RApID Project WPF\Main";
#endif

                    _emailMessage.Body = string.IsNullOrWhiteSpace(body) ?
                                         File.ReadAllText($@"{initialPath}\Resources\ExceptionEmailTemplate.html")
                                         .Replace("[ExceptionType]", WebUtility.HtmlEncode(exception?.GetType().ToString() ?? ""))
                                         .Replace("[ExceptionMessage]", WebUtility.HtmlEncode(exception?.Message.ToString() ?? ""))
                                         .Replace("[ExceptionStackTrace]", WebUtility.HtmlEncode(exception?.StackTrace.ToString() ?? ""))
                    : body;

                    #region Get Smtp thing
                    string eeptConnString = csObjectHolder.csObjectHolder.ObjectHolderInstance().EEPTConnectionString;
                    string query          = "SELECT Name FROM EmailServers";
                    string smtpClient     = sqlClass.SQLGet_String(query, eeptConnString);

                    SmtpClient smtp = new SmtpClient(smtpClient);;
                    //System.Net.ServicePointManager.MaxServicePointIdleTime = 1;

                    string sExMessage = "";
                    int    iTries     = 0;

                    while (true)
                    {
                        try
                        {
                            smtp = new SmtpClient(smtpClient)
                            {
                                Timeout = 3000
                            };
                            smtp.Send(_emailMessage);
                            break;
                        }
                        catch (Exception ex)
                        {
                            sExMessage = ex.Message;
                        }
                        finally
                        {
                            smtp.Dispose();
                        }

                        iTries++;

                        if (iTries == 3)
                        {
                            throw new Exception(sExMessage);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Couldn't send error email...\nPlease contact Jay Whaley or Dexter Glanton.",
                                "Critical Failure", MessageBoxButton.OK, MessageBoxImage.Error);
                csExceptionLogger.csExceptionLogger.Write("Mailman_Error", ex);
                return(false);
            }
            return(true);
        }
コード例 #58
0
        public string[] Handle(string[] args)
        {
            var messages = new List <string>();

            if (!ArgumentsAreValid(args, messages))
            {
                return(messages.ToArray());
            }

            SplicedContainer splicedUsernameAndMessage = Utils.SplicedContainerForIndexOfAray(args, 0);
            string           username = splicedUsernameAndMessage.Spliced;
            string           message  = String.Join(" ", splicedUsernameAndMessage.RemainingArray);

            Account to = AccountsRepository.GetAccountForUsername(username);

            if (to == null)
            {
                return(new string[]
                {
                    String.Format("Username \"{0}\" could not be found in the system. Have you loaded the save file?", username)
                });
            }

            List <string> result = new List <string>();

            try
            {
                MailMessage mm = new MailMessage()
                {
                    From    = new MailAddress("*****@*****.**", "Dan Scott"),
                    Subject = "Nudge",
                    Body    = message
                };

                mm.To.Add(new MailAddress(to.Email, to.Username));
                using (SmtpClient client = new SmtpClient("exchange.wpcsoft.com"))
                {
                    client.Send(mm);
                }

                return(new string[]
                {
                    String.Format("Message \"{0}\" was successfully sent to {1}.", mm.Body.ToString(), to.Email)
                });
            }
            catch (InvalidOperationException e)
            {
                result.Add("Server host is undefined. Error: " + e.Message);
            }
            catch (SmtpFailedRecipientException e)
            {
                result.Add("Recepient does not have a mailbox. Error: " + e.Message);
            }
            catch (SmtpException e)
            {
                result.Add("Smtp sever host could not be found. Error: " + e.Message);
            }
            catch (Exception e)
            {
                result.Add("Error: " + e.Message.ToString());
            }
            return(result.ToArray());
        }
コード例 #59
0
        public ActionResult Index(int reportID)
        {
            ViewBag.reportID = reportID;

            List <vm_dailyReportByReportID> dailyReportByID = new List <vm_dailyReportByReportID>();
            List <string> recipientList = new List <string>();

            string        mainconn = ConfigurationManager.ConnectionStrings["allpaxServiceRecordEntities"].ConnectionString;
            SqlConnection sqlconn  = new SqlConnection(mainconn);

            sqlconn.Open();

            string sqlquery1 =
                "SELECT tbl_dailyReport.dailyReportID, tbl_dailyReport.jobID, tbl_subJobTypes.description, tbl_dailyReport.date, " +
                "tbl_Jobs.customerContact,tbl_customers.customerName, tbl_customers.address, tbl_dailyReport.equipment, " +
                "tbl_dailyReport.startTime, tbl_dailyReport.endTime, tbl_dailyReport.lunchHours, tbl_customers.customerCode " +

                "FROM tbl_dailyReport " +

                "INNER JOIN " +
                "tbl_Jobs ON tbl_Jobs.jobID = tbl_dailyReport.jobID " +
                "INNER JOIN " +
                "tbl_customers ON tbl_customers.customerCode = tbl_Jobs.customerCode " +
                "INNER JOIN " +
                "tbl_jobSubJobs ON tbl_jobSubJobs.jobID = tbl_Jobs.jobID " +
                "INNER JOIN " +
                "tbl_subJobTypes ON tbl_subJobTypes.subJobID = tbl_jobSubJobs.subJobID " +

                "WHERE " +

                "tbl_dailyReport.subJobID = tbl_subJobTypes.subJobID " +
                "AND " +
                "tbl_dailyReport.dailyReportID LIKE @reportID";

            SqlCommand sqlcomm1 = new SqlCommand(sqlquery1, sqlconn);

            sqlcomm1.Parameters.AddWithValue("@reportID", reportID);
            SqlDataAdapter sda1 = new SqlDataAdapter(sqlcomm1);
            DataTable      dt1  = new DataTable();

            sda1.Fill(dt1);
            foreach (DataRow dr1 in dt1.Rows)
            {
                vm_dailyReportByReportID vm_dailyReportByReportID = new vm_dailyReportByReportID();

                vm_dailyReportByReportID.dailyReportID   = (int)dr1[0];
                vm_dailyReportByReportID.jobID           = dr1[1].ToString();
                vm_dailyReportByReportID.description     = dr1[2].ToString();
                vm_dailyReportByReportID.date            = String.Format("{0:yyyy-MM-dd}", dr1[3]);
                vm_dailyReportByReportID.customerContact = dr1[4].ToString();
                vm_dailyReportByReportID.customerName    = dr1[5].ToString();
                vm_dailyReportByReportID.address         = dr1[6].ToString();
                vm_dailyReportByReportID.equipment       = dr1[7].ToString();
                vm_dailyReportByReportID.startTime       = dr1[8].ToString();
                vm_dailyReportByReportID.endTime         = dr1[9].ToString();
                vm_dailyReportByReportID.lunchHours      = (int)dr1[10];
                vm_dailyReportByReportID.customerCode    = dr1[11].ToString();
                vm_dailyReportByReportID.names           = namesByTimeEntryID(vm_dailyReportByReportID.dailyReportID);
                vm_dailyReportByReportID.shortNames      = shortNamesByTimeEntryID(vm_dailyReportByReportID.dailyReportID);

                vm_dailyReportByReportID.jobCorrespondentName  = jobCrspdtNameByJobID(vm_dailyReportByReportID.jobID);
                vm_dailyReportByReportID.jobCorrespondentEmail = jobCorrespondentEmailByTimeEntryID(vm_dailyReportByReportID.jobID);

                recipientList = vm_dailyReportByReportID.jobCorrespondentEmail;

                dailyReportByID.Add(vm_dailyReportByReportID);
            }

            sqlconn.Close();

            string recipientListStr = string.Join(", ", recipientList);

            string html = ViewRenderer.RenderView("~/views/dailyReportByReportIDPrint/index.cshtml", dailyReportByID);

            SmtpClient smtp = new SmtpClient();

            smtp.Host                  = "smtp.gmail.com";
            smtp.Port                  = 587;
            smtp.EnableSsl             = true;
            smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new NetworkCredential("*****@*****.**", "Allpax_1234");

            string body = html;

            using (var message = new MailMessage("*****@*****.**", recipientListStr))
            {
                message.Subject    = "Test";
                message.Body       = body;
                message.IsBodyHtml = true;
                smtp.Send(message);
            }

            return(View(dailyReportByID));
        }