Exemplo n.º 1
0
    public  void Send(string toEmailAddress, string vendorName)
    {
        try
        {
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
            //string emailAddress = ConfigurationManager.AppSettings["errReporting"];
            string strMessageBody = GetEmailBody(vendorName);
            string strSubject = "Vendor approved notification.";

            //MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromAddress"]);
            MailAddress fromAddress = new MailAddress("*****@*****.**");
            // smtpClient.Host = ConfigurationManager.AppSettings["hostAddress"];
            smtpClient.Port = 587;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.UseDefaultCredentials = false;

            message.From = fromAddress;
            // To address collection of MailAddress
            message.To.Add(toEmailAddress);
            message.Subject = strSubject;
            message.IsBodyHtml = true;

            // Message body content
            message.Body = strMessageBody;
            // Send SMTP mail
            smtpClient.Send(message);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Exemplo n.º 2
0
    public static void sendmail(string msg,string emailtosend)
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        MailAddress fromAddress = new MailAddress("mail.capexbd.com", "CapexBD Marketing Tool");

        smtpClient.Host = "mail.capexbd.com";
        //Default port will be 25
        smtpClient.Port = 25;
        //From address will be given as a MailAddress Object
        message.From = fromAddress;
        // To address collection of MailAddress
        message.To.Add(emailtosend);
        message.Subject = "CapexBD Demo Wanted.";

        message.IsBodyHtml = true; ;

        // Message body content
        String bodymessage = msg;
        message.Body = bodymessage;

        // Send SMTP mail
        try
        {
            smtpClient.Send(message);
        }
        catch (Exception e)
        {

        }
    }
Exemplo n.º 3
0
 private void SendEmail(string subject, string body, string replyEmail, bool isHTML)
 {
     int portNumber;
     int.TryParse(System.Configuration.ConfigurationManager.AppSettings["SMTPServerPort"],
                  out portNumber);
     SmtpClient client;
     if (portNumber > 0)
     {
         client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SMTPServer"], portNumber);
     }
     else
     {
         client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["SMTPServer"]);
     }
     MailAddress from =
         new MailAddress(System.Configuration.ConfigurationManager.AppSettings["FromEmail"]);
     MailAddress to = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["ToEmail"].Trim());
     MailMessage message = new MailMessage(from, to);
     message.ReplyToList.Add(new MailAddress(replyEmail));
     message.Body = body;
     message.IsBodyHtml = isHTML;
     message.Subject = subject;
     message.BodyEncoding = System.Text.Encoding.UTF8;
     message.SubjectEncoding = System.Text.Encoding.UTF8;
     if (System.Configuration.ConfigurationManager.AppSettings["EmailAccountPassword"].Trim() != "")
     {
         client.Credentials =
             new System.Net.NetworkCredential(
                 System.Configuration.ConfigurationManager.AppSettings["FromEmail"],
                 System.Configuration.ConfigurationManager.AppSettings["EmailAccountPassword"]);
     }
     client.Send(message);
 }
Exemplo n.º 4
0
    public static string SendMail(string toList, string from, string ccList, string subject, string body)
    {
        MailMessage message = new MailMessage();
        SmtpClient smtpClient = new SmtpClient();
        string msg = string.Empty;
        try
        {
            MailAddress fromAddress = new MailAddress(from);
            message.From = fromAddress;
            message.To.Add(toList);
            if (ccList != null && ccList != string.Empty)
                message.CC.Add(ccList);
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;
            smtpClient.Host = "smtp.gmail.com";   // gmail како smtp клиент
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "JoPeDrTrNiJoSDSM");

            smtpClient.Send(message);
            msg = "Пораката е успешно пратена!";
        }
        catch (Exception ex)
        {
            msg = ex.Message;
        }
        return msg;
    }
Exemplo n.º 5
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (this.IsValid)
        {
            BasePrincipal _user = BasePrincipal.GetByEmail(txt_Email.Text, ConfigurationManager.ConnectionStrings["TopRockConnection"].ConnectionString);
            if (_user != null)
            {
                MailMessage _mail = new MailMessage();
                MailAddress _madd = new MailAddress(((TopRockUser)_user.Identity).Email);
                _mail.To.Add(_madd);
                _mail.Subject = ConfigurationManager.AppSettings["ForgotPasswSubject"];
                _mail.IsBodyHtml = false;
                _mail.Body = String.Format(ConfigurationManager.AppSettings["ForgotPasswBody"],
                    ((TopRockUser)_user.Identity).Email, ((TopRockUser)_user.Identity).Password);

                SmtpClient _smtp = new SmtpClient();
                _smtp.Send(_mail);
                lblMsg.Text = "Your passsword has been sent";
            }
            else
            {
                lblMsg.Text = "Email address is not valid";
            }
        }
    }
Exemplo n.º 6
0
    public void send_mail()
    {
        MailMessage message = new MailMessage();
        SmtpClient smtpClient = new SmtpClient();
        string msg = string.Empty;
        try
        {
            MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["NLemailfrom"].ToString());
            message.From = fromAddress;
            message.To.Add("*****@*****.**");
            message.Subject = "hello";
            message.IsBodyHtml = true;
            message.Body = "ddd";
            smtpClient.Host = "relay-hosting.secureserver.net";   //-- Donot change.
            smtpClient.Port = 25; //--- Donot change
            smtpClient.EnableSsl = false;//--- Donot change
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["NLemailfrom"].ToString(), ConfigurationManager.AppSettings["NLemailpassword"].ToString());

            smtpClient.Send(message);

            // lblConfirmationMessage.Text = "Your email successfully sent.";
        }
        catch (Exception ex)
        {
            msg = ex.Message;
        }
    }
Exemplo n.º 7
0
    public static void Send(string toEmail, string toTen, string subject, string body, string fromEmail, string fromName)
    {
        var fromAddress = new MailAddress(fromEmail, fromName);
        var toAddress = new MailAddress(toEmail, toTen);

        var smtp = new SmtpClient
        {
            Host = "email-smtp.eu-west-1.amazonaws.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("AKIAINTSEWVCFL5UA2MQ", "AuwQb9Mbo72AaPuJMGi0ZBw7ozgxGPtwUei60NuueMWB"),
            Timeout = 20000
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body,
            BodyEncoding = System.Text.Encoding.UTF8,
            SubjectEncoding = System.Text.Encoding.UTF8,
            IsBodyHtml = true

        })
        {
            try
            {
                smtp.Send(message);
            }
            catch (SmtpException ex)
            {

            }
        }
    }
    protected void btn2_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            MailAddress fromAddress = new MailAddress("*****@*****.**");
            mailMessage.From = fromAddress;

            foreach (GridViewRow row in gvImages.Rows)
            {
                MailAddress to = new MailAddress(row.Cells[3].Text);
                mailMessage.To.Add(to);

            }

            mailMessage.Body = message.Text;
            mailMessage.IsBodyHtml = true;
            mailMessage.Subject = subject.Text;
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = "localhost";
            smtpClient.Send(mailMessage);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert(' mail sent')", true);
            subject.Text = string.Empty;
            message.Text = string.Empty;
                
        }
         catch (Exception ex)
         {
             ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert(' mail not sent')", true);            
         }

    }
Exemplo n.º 9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        emailid.Value = Request["email"].ToString();
            if (emailid.Value != "")
            {

                //check email first
                userMasterBO.email = emailid.Value;
                if (!IsPostBack)
                {
                bool valid = userMasterBAL.checkValidEmailToResetPassword(userMasterBO);

                if (valid == true)
                {

                    // first create the passcode here. to generate passcode  i have to write the storedprocedure

                    // now first check  passcode is null or not.

                    Random rnd = new Random();
                    int passcode = rnd.Next(00000000, 99999999);
                    userMasterBO.passcode = passcode;

                    //code to send email
                    MailMessage vMsg = new MailMessage();
                    MailAddress vFrom = new MailAddress("*****@*****.**", "RATEmymp");
                    vMsg.From = vFrom;
                    vMsg.To.Add(emailid.Value); //This is a string which contains delimited :semicolons for multiple
                    vMsg.Subject = "Passcode to reset Password in rateMyMp"; //This is the subject;
                    vMsg.Body = passcode.ToString(); //This is the message that needs to be passed.

                    //Create an object SMTPclient for relaying
                    // SmtpClient vSmtp = new SmtpClient();
                    SmtpClient vSmtp = new SmtpClient("smtp.gmail.com", 587);
                    vSmtp.Host = ConfigurationManager.AppSettings["SMTP"];
                    vSmtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]);
                    //vSmtp.Credentials = new System.Net.NetworkCredential("lovelybatch", ConfigurationManager.AppSettings["FROMPWD"]);
                    vSmtp.EnableSsl = true;
                    vSmtp.Send(vMsg);

                    //now store same passcode in database under corresponding email address
                    bool success = userMasterBAL.insertPasscode(userMasterBO);
                    if (success == true)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "myfunction", "information()", true);
                    }
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
                }
            }
            else
            {
                //redirect to home page.
                Response.Redirect("Default.aspx");

            }
    }
Exemplo n.º 10
0
    protected void Submit_Click(object sender, EventArgs e)
    {
        MailAddress mailFrom = new MailAddress("*****@*****.**");
        MailAddress mailTo = new MailAddress("*****@*****.**");

        MailMessage emailMessage = new MailMessage(mailFrom, mailTo);

        emailMessage.Subject = "Unsubscribe";
        emailMessage.Body += "<br>Email: " + email.Text;

        emailMessage.IsBodyHtml = false;

        SmtpClient myMail = new SmtpClient();
        myMail.Host = "localhost";
        myMail.DeliveryMethod = SmtpDeliveryMethod.Network;

        //myMail.Port = 25;
        NetworkCredential SMTPUserInfo = new NetworkCredential("*****@*****.**", "!p3Learning", "pinnacle3learning.com");
        //myMail.UseDefaultCredentials = false;
        myMail.Credentials = SMTPUserInfo;

        myMail.Send(emailMessage);

        MultiView1.ActiveViewIndex = 1;
    }
Exemplo n.º 11
0
    public void SendEmail(string mailSubject, string mailBody, string users, string username, string password,string host,string emal)
    {
        try
        {

            MailAddress ma= new MailAddress(users,"ray");

            //Preparing the mailMessage
            MailMessage mail = new MailMessage();
            mail.Subject = mailSubject;
            mail.From = ma;
            mail.To.Add(emal);
            mail.Body = mailBody+"please login to score those articles";
            mail.IsBodyHtml = true;

            //Preparing the smtp client to send the mailMessage

            SmtpClient smtp = new SmtpClient(host);

            smtp.Credentials = new System.Net.NetworkCredential
                 (username, password);
            smtp.EnableSsl = true;
            smtp.Port = 587;

            //Sending message using smtp client
            smtp.Send(mail);
            cs.writelog(" auto email has send to  " + username+" on "+DateTime.Now.ToString());
            Label1.Text="Your Message has been sent successfully";
        }
        catch (Exception ex)
        {
            Label1.Text="Message Delivery Fails"+ex.Message;

        }
    }
Exemplo n.º 12
0
    public void Envio(Correo c)
    {
        MailMessage mensaje1 = new MailMessage();
            MailAddress dirCorreo = new MailAddress(c.Origen);

            SmtpClient cliente = new SmtpClient("smtp.1and1.es",25);
            NetworkCredential nc = new NetworkCredential(usuario, password);

            cliente.Credentials = nc;

            foreach (string x in c.Destinatarios)
            {
                mensaje1.To.Add(x);
            }

            if (copiaOculta != null)
            {
                mensaje1.Bcc.Add(copiaOculta);
            }

            mensaje1.IsBodyHtml = true;
            mensaje1.From = dirCorreo;
            mensaje1.Subject = c.Asunto;
            mensaje1.Body = c.Cuerpo;

            cliente.Send(mensaje1);
    }
Exemplo n.º 13
0
    public static string SendMail(string gooLogin, string gooPassword, string toList, string from, string ccList, string subject, string body)
    {
        MailMessage message = new MailMessage();
        SmtpClient smtpClient = new SmtpClient();
        string msg = string.Empty;
        try
        {
        MailAddress fromAddress = new MailAddress(from);
        message.From = fromAddress;
        message.To.Add(toList);

        if (ccList != null && ccList != string.Empty)
            message.CC.Add(ccList);

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

        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.UseDefaultCredentials = true;
        smtpClient.Credentials = new System.Net.NetworkCredential(gooLogin, gooPassword);

        smtpClient.Send(message);
        msg = "Vaša poruka je uspješno poslana! Hvala!";
        }
        catch (Exception ex)
        {
        msg = ex.Message;
        }
        return msg;
    }
Exemplo n.º 14
0
    public static void sendMail(String message, String mailKlant, String naamKlant)
    {
        MailAddress fromAddress = new MailAddress("*****@*****.**", "VPRtravel");//"*****@*****.**";
        MailAddress toAddress = new MailAddress(mailKlant, naamKlant); //"*****@*****.**";

        //Create the MailMessage instance
        MailMessage myMailMessage = new MailMessage(fromAddress, toAddress);

        //Assign the MailMessage's properties
        myMailMessage.Subject = "Confirmation";
        myMailMessage.Body = message;
        myMailMessage.IsBodyHtml = true;

        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("*****@*****.**", "69JNhL");

        //Send the MailMessage (will use the Web.config settings)
        client.Send(myMailMessage);
    }
    //Now in ppClass_sb.cs
    //get expired permits and reset spots to unoccupied
    //private void _resetSpots()
    //{
    //    //get expired spots
    //    var expiredSpots = objPark.getExpiredPermits(DateTime.Now);
    //    foreach (var spot in expiredSpots)
    //    {
    //       var spotSingle = objPark.getSpotBySpot(spot.spot);
    //    }
    //}
    //Send Email Receiptfd
    protected void sendReceipt(DateTime _timeExp, string _spot)
    {
        //This is the script provided by my hosting to send mail (Source URL: https://support.gearhost.com/KB/a777/aspnet-form-to-email-example.aspx?KBSearchID=41912)
        try
        {
            //Create the msg object to be sent
            MailMessage msg = new MailMessage();
            //Add your email address to the recipients
            msg.To.Add(txt_email.Text);
            //Configure the address we are sending the mail from
            MailAddress address = new MailAddress("*****@*****.**");
            msg.From = address;
            //Append their name in the beginning of the subject
            msg.Subject = "Your KDH Parking Reciept";
            msg.Body = "Thank you for parking with us. You are parked in " + _spot + " and your permit expires at " + _timeExp.ToString(@"hh\:mm\:ss") + ".";

            //Configure an SmtpClient to send the mail.
            SmtpClient client = new SmtpClient("mail.stevebosworth.ca");
            client.EnableSsl = false; //only enable this if your provider requires it
            //Setup credentials to login to our sender email address ("UserName", "Password")
            NetworkCredential credentials = new NetworkCredential("*****@*****.**", "Pa55w0rd!");
            client.Credentials = credentials;

            //Send the msg
            client.Send(msg);
        }
        catch
        {
            //If the message failed at some point, let the user know

            lbl_message.Text = "Your message failed to send, please try again.";
        }
    }
Exemplo n.º 16
0
        /// <summary>
        ///     创建邮箱账号
        /// </summary>
        /// <returns>邮箱账号</returns>
        public static MailAddress CreateMailAddress()
        {
            var mailAddress = new MailAddress();

            mailAddress.GenerateNewIdentity();
            return mailAddress;
        }
Exemplo n.º 17
0
    /// <summary>
    /// Mail potwierdzający wysyłke zamówienia
    /// </summary>
    /// <param name="a_strMailAddress"></param>
    /// <param name="a_gActivationCode"></param>
    /// <param name="a_ctlOwner"></param>
    public static void SendShippedOrderEmail(string emailAddress, Order order)
    {
        MailDefinition mailDefinition = new MailDefinition();
        mailDefinition.BodyFileName = "~/MailTemplates/ZamowienieWyslane.html";
        mailDefinition.IsBodyHtml = true;
        mailDefinition.Subject = "Nazwa firmy - Zamówienie wysłano";
        IDictionary replacements = new Hashtable();

        //Dodawanie znaczników, które zostaną podmienione w szablonie maila na właściwe wartości
        replacements.Add("<%OrderDate%>", order.OrderDate.ToString("dd-MM-yyyy"));
        Address address = order.CustomerFacility.Address;
        String strAddress = "ul. " + address.Street +
            address.HouseNr + "/" + address.ApartmentNr + ", " +
            address.ZipCode + " " + address.City.Name + " " + address.Country.Name;
        replacements.Add("<%Address%>", strAddress);
        replacements.Add("<%Total%>", order.Total.ToString("0.00 zł"));

        MailMessage msg = mailDefinition.CreateMailMessage(emailAddress, replacements, new Panel());
        MailAddress mailFrom = new MailAddress(msg.From.Address, "Nazwa firmy");
        msg.From = mailFrom;

        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;
        client.Send(msg);
    }
Exemplo n.º 18
0
    public bool Retrieve_Password(string email, string pass)
    {
        string _email = email;
        string _pass = pass;

        try
        {
            //Create the email message

            MailAddress from = new MailAddress("*****@*****.**");
            MailAddress to = new MailAddress(email.Trim());
            MailMessage mailObj = new MailMessage(from, to);
            mailObj.Subject = "Password Recovery";
            //Create the message body
            mailObj.Body += "<h2>Password recovery request from Weservullc.com</h2><br /> "
                + "<p>Your password is: " + _pass + "</p>";

            mailObj.IsBodyHtml = true;

            //uncomment these lines when loading to GoDaddy Servers.

            SmtpClient smtp = new SmtpClient(SERVER);
            smtp.Send(mailObj);
            mailObj = null;
            return true;
        }
        catch(SmtpException se)
        {
            return false;
        }
    }
Exemplo n.º 19
0
    public static void Send(string Body,string subject, string Address)
    {
        try
        {

        SmtpClient smtpClient = new SmtpClient();
        NetworkCredential basicCredential = new NetworkCredential("nephromorsys", "Orr190557");
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress("*****@*****.**");

        //smtpClient.Credentials = new NetworkCredential("nephromorsys", "Orr190557");
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;

        message.From = fromAddress;
        message.Subject = subject;
        //Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "<h1> " + Body +"</h1>";
        message.To.Add(Address);
        //message.To.Add("*****@*****.**");
        //message.To.Add("*****@*****.**");

            smtpClient.Send(message);
        }
        catch (Exception ex)
        {
            //Error, could not send the message
            //Response.Write(ex.Message);
            throw ex;
        }
    }
Exemplo n.º 20
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage msg = new MailMessage();
        MailAddress mailadd = new MailAddress("*****@*****.**","Amita Shukla");
        msg.From = mailadd;
        msg.To.Add(new MailAddress(TextBox1.Text));
        msg.Subject = TextBox2.Text;
        msg.Body = TextBox4.Text;
        if (FileUpload1.HasFile)
        {
            msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        NetworkCredential nkc = new NetworkCredential("*****@*****.**", "*******");
        smtp.Credentials = nkc;
        smtp.EnableSsl = true;

        try
        {
            smtp.Send(msg);
            Label5.Text = "Email sent successfully";
        }
        catch(Exception ex)
        {
            Label5.Text = ex.Message;
        }
    }
Exemplo n.º 21
0
    /// <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;
    }
Exemplo n.º 22
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     string email = TextBox1.Text;
     string body = TextBox2.Text;
     MailMessage objmail = new MailMessage("*****@*****.**", email);
     MailAddress from = new MailAddress("*****@*****.**");
     MailAddress to = new MailAddress(email);
     objmail.Body = body;
     objmail.From = from;
     objmail.Subject = "techsrijan 2012";
     objmail.IsBodyHtml = true;
     SmtpClient sendmail = new SmtpClient("localhost");
     sendmail.EnableSsl = true;
     NetworkCredential auth = new NetworkCredential("*****@*****.**","techsrijan2012");
     sendmail.Credentials = auth;
     try
     {
         sendmail.Send(objmail);
         lbl_status.Text = "Message Sent successfully";
         lbl_status.Visible= true;
     }
     catch (Exception)
     {
         lbl_status.Text = "Message Failed";
         lbl_status.Visible = true;
     }
 }
Exemplo n.º 23
0
        public void PrepareHeaders_WithReplyToNull_AndReplyToListSet_ShouldUseReplyToList()
        {
            MailAddress m = new MailAddress("*****@*****.**");
            MailAddress m2 = new MailAddress("*****@*****.**");
            MailAddress m3 = new MailAddress("*****@*****.**");

            _message.ReplyToList.Add(m);
            _message.ReplyToList.Add(m2);
            _message.ReplyToList.Add(m3);

            _message.From = new MailAddress("*****@*****.**");

            _message.PrepareHeaders(true, false);

            Assert.Equal(3, _message.ReplyToList.Count);

            string[] s = _message.Headers.GetValues("Reply-To");
            Assert.Equal(1, s.Length);

            Assert.True(s[0].Contains("*****@*****.**"));
            Assert.True(s[0].Contains("*****@*****.**"));
            Assert.True(s[0].Contains("*****@*****.**"));

            Assert.Null(_message.ReplyTo);
        }
Exemplo n.º 24
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());
        }
    }
Exemplo n.º 25
0
        public void PrepareHeaders_WithReplyToListSet_AndReplyToHeaderSetManually_ShouldEnforceReplyToListIsSingleton()
        {
            MailAddress m = new MailAddress("*****@*****.**");
            MailAddress m2 = new MailAddress("*****@*****.**");
            MailAddress m3 = new MailAddress("*****@*****.**");

            _message.ReplyToList.Add(m);
            _message.ReplyToList.Add(m2);
            _message.ReplyToList.Add(m3);

            _message.Headers.Add("Reply-To", "*****@*****.**");

            _message.From = new MailAddress("*****@*****.**");

            _message.PrepareHeaders(true, false);

            Assert.True(_message.ReplyToList.Count == 3, "ReplyToList did not contain all email addresses");

            string[] s = _message.Headers.GetValues("Reply-To");
            Assert.Equal(1, s.Length);

            Assert.True(s[0].Contains("*****@*****.**"));
            Assert.True(s[0].Contains("*****@*****.**"));
            Assert.True(s[0].Contains("*****@*****.**"));
            Assert.False(s[0].Contains("*****@*****.**"));

            Assert.Null(_message.ReplyTo);
        }
Exemplo n.º 26
0
Arquivo: Email.cs Projeto: 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;
     }
 }
Exemplo n.º 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 = "";
        }
    }
Exemplo n.º 28
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);
    }
 // Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
 public void SendHTMLMail()
 {
     StreamReader reader = new StreamReader(Server.MapPath("~/HTMLPage.htm"));
     string readFile = reader.ReadToEnd();
     string myString = "";
     myString = readFile;
     myString = myString.Replace("$$Admin$$", "Suresh Dasari");
     myString = myString.Replace("$$CompanyName$$", "Dasari Group");
     myString = myString.Replace("$$Email$$", "*****@*****.**");
     myString = myString.Replace("$$Website$$", "http://www.aspdotnet-suresh.com");
     MailMessage Msg = new MailMessage();
     MailAddress fromMail = new MailAddress("*****@*****.**");
     // Sender e-mail address.
     Msg.From = fromMail;
     // Recipient e-mail address.
     Msg.To.Add(new MailAddress("*****@*****.**"));
     // Subject of e-mail
     Msg.Subject = "Send Mail with HTML File";
     Msg.Body = myString.ToString();
     Msg.IsBodyHtml = true;
     string sSmtpServer = "";
     sSmtpServer = "10.2.69.121";
     SmtpClient a = new SmtpClient();
     a.Host = sSmtpServer;
     a.Send(Msg);
     reader.Dispose();
 }
    //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>");
    }
Exemplo n.º 31
0
        public string SendSmtpMsg(MailAddress fromAddress, string subject, string message, List <MailAddress> to, int?id, int?pid, List <LinkedResource> attachments = null, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];
            var msg          = new MailMessage();

            if (fromAddress == null)
            {
                fromAddress = Util.FirstAddress(senderrorsto);
            }

            var fromDomain = DefaultFromDomain;

            msg.From = new MailAddress(fromDomain, fromAddress.DisplayName);
            msg.ReplyToList.Add(fromAddress);
            if (cc != null)
            {
                foreach (var a in cc)
                {
                    msg.ReplyToList.Add(a);
                }
                if (!msg.ReplyToList.Contains(msg.From) && msg.From.Address.NotEqual(fromDomain))
                {
                    msg.ReplyToList.Add(msg.From);
                }
            }

            msg.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            msg.Headers.Add(XBvcms, XBvcmsHeader(id, pid));

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    msg.AddAddr(ma);
                }
            }

            msg.Subject = subject;
            var badEmailLink = "";

            if (msg.To.Count == 0 && to.Any(tt => tt.Host == "nowhere.name"))
            {
                return(null);
            }
            if (msg.To.Count == 0)
            {
                msg.AddAddr(msg.From);
                msg.AddAddr(Util.FirstAddress(senderrorsto));
                msg.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex    = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var text     = regex.Replace(message, string.Empty);
            var textview = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, MediaTypeNames.Text.Plain);

            textview.TransferEncoding = TransferEncoding.Base64;
            msg.AlternateViews.Add(textview);

            var html = badEmailLink + message + CcMessage(cc);

            using (var htmlView = AlternateView.CreateAlternateViewFromString(html, Encoding.UTF8, MediaTypeNames.Text.Html))
            {
                htmlView.TransferEncoding = TransferEncoding.Base64;
                if (attachments != null)
                {
                    foreach (var a in attachments)
                    {
                        htmlView.LinkedResources.Add(a);
                    }
                }
                msg.AlternateViews.Add(htmlView);

                var smtp = Smtp();
                smtp.Send(msg);
            }
            return(fromDomain);
        }
Exemplo n.º 32
0
        private void SendMail(ArrayList alist, string id, string sn)
        {
            try
            {
                string mailaddress = "";//this.DataList1.Items.Count.ToString() ;
                string to_mail     = "";
                SmoothEnterprise.Database.DataSet rss = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                rss.Open("select email from EIPA.dbo.EngineeringTest_head a  left join EIPA.dbo.dguser b on a.add_user=b.id where a.id='" + Request.QueryString["id"] + "'   ").ToString();
                if (!rss.EOF)
                {
                    mailaddress = rss["email"].ToString();
                }
                //string MailCC = "";
                //if (alist.Count != 0)
                //{
                //    foreach (string s in alist)
                //    {
                //        MailCC += s + ";";
                //    }
                //}
                //int i = 0;
                //foreach (string mail in alist)
                //{
                //    if (i == 0)
                //        to_mail = mail;
                //    else
                //        mailaddress += mail + ";";
                //}
                //mailaddress = mailaddress.Substring(1, mailaddress.Length - 1);
                //mailaddress = this.CurrentUser.EMail + ";" + mailaddress;


                String      ques;
                MailAddress from = new MailAddress("*****@*****.**", "ePortal(員工入口網站)");

                MailAddress to = new MailAddress(mailaddress);
                //if (string.IsNullOrEmpty(MailCC))
                //{
                //    MailAddress cc = new MailAddress(MailCC);
                //}
                //正式的時候記得demark
                //MailAddress bcc = new MailAddress("*****@*****.**");
                //MailAddress bcc = new MailAddress("*****@*****.**");
                //MailAddress bccrage = new MailAddress("*****@*****.**");

                MailMessage message = new MailMessage(from, to);
                //message.Bcc.Add(bcc);
                //message.Bcc.Add(bccrage);

                message.To.Add(mailaddress);
                DateTime de = Convert.ToDateTime(this.FIELD_expect_date.Text);
                ques = "  您好: " +
                       "<BR>NPI 試模計劃系統現有一筆資料通知您 " +
                       " <BR>詳細資料:<a href=\"http://eip.minaik.com.tw/NPI_TryoutFeedback/NPI_TryoutFeedbackEdit.aspx?rowno=" + id + "\">http://eip.minaik.com.tw/NPI/NPI_TryoutFeedbackView.aspx</a>" +
                       " <BR>==================================================================================================" +
                       " <BR><table border=1 width=500>" +
                       " <tr>" +
                       " <td align=center style=background-color: #f0f0f0;>表單編號</td><td align=left >" + sn + "</td>" +
                       " </tr>" +
                       " <tr>" +
                       " <td align=center style=background-color: #f0f0f0;>成品料號</td><td align=left >" + this.cima01.Text + "</td>" +
                       " </tr>" +
                       " </table>" +
                       " <BR>==================================================================================================" +
                       " <BR>如您想了解更多有關員工入口網站的資訊請點選以下連結進入" +
                       " <BR><a href=\"http://eip.minaik.com.tw/\">員工入口網站</a>" +
                       " <BR>感謝您對員工入口網站的支持與愛護。<font color=\"red\">因本信件為系統自動發送,請勿直接以此郵件回覆</font>";

                message.Subject = "【通知】EIP模具試作計劃系統單號 - " + sn + " 成品料號-" + this.cima01.Text + "";

                message.IsBodyHtml = true;

                message.Body = ques;


                SmtpClient client = new SmtpClient("192.168.0.12");

                client.Send(message);

                //}
                //rss.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Exemplo n.º 33
0
        public static async Task <bool> SendEmail(MailAddress onBehalfOf, List <string> toAddress, List <string> ccAddress, List <string> bccAddress, string subject, string htmlBody, string plainBody = null, List <string> attachments = null, bool ignoreError = false)
        {
            SmtpClient smtpClient = new SmtpClient {
            };

            MailMessage message = new MailMessage();

            try
            {
                message.From = new MailAddress(Common.Email.Email_Default);
                toAddress?.ForEach(address => message.To.Add(address));
                ccAddress?.ForEach(address => message.CC.Add(address));
                bccAddress?.ForEach(address => message.Bcc.Add(address));

                message.Subject = subject?.Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ");

                if (onBehalfOf != null)
                {
                    message.ReplyToList.Add(onBehalfOf.Address);
                    message.From = onBehalfOf;
                }

                if (plainBody != null)
                {
                    message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Plain));
                }

                if (htmlBody != null)
                {
                    message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlBody, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html));
                }

                attachments?.ForEach(attachment =>
                {
                    if (File.Exists(attachment))
                    {
                        Attachment data = new Attachment(attachment, MediaTypeNames.Application.Octet);

                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.CreationDate       = File.GetCreationTime(attachment);
                        disposition.ModificationDate   = File.GetLastWriteTime(attachment);
                        disposition.ReadDate           = File.GetLastAccessTime(attachment);
                        message.Attachments.Add(data);
                    }
                });

                await Task.Run(() => smtpClient.Send(message));

                message.Dispose();
                return(true);
            }
            catch (Exception ex)
            {
                if (ignoreError == false)
                {
                    string errorMessage = "Error sending email";
                    errorMessage += "\n" + "To: ";
                    errorMessage  = toAddress?.Aggregate(errorMessage, (current, address) => current + address);
                    errorMessage += "\n" + "CC: ";
                    errorMessage  = ccAddress?.Aggregate(errorMessage, (current, address) => current + address);
                    errorMessage += "\n" + "Bcc: ";
                    errorMessage  = bccAddress?.Aggregate(errorMessage, (current, address) => current + address);
                    errorMessage += "\n" + "Subject: " + subject;
                    errorMessage += "\n\n" + "HtmlBody: " + htmlBody;
                    errorMessage += "\n\n" + "PlainBody: " + plainBody;
                    errorMessage += "\n\n" + "Error: " + ex.Message;
                    throw new Exception(errorMessage);
                }

                return(false);
            }
        }
Exemplo n.º 34
0
        public ActionResult Create([Bind(Include = "LT,Compound_Sequence_Code,Compound_Name,Quantity,Date_Arrived,Received_By,Date_Due,Appearance,Indicated_Weight,Molecular_Mass,Actual_Weight,MTD,Confirmation_Date,Confirmation_Time,Work_Order_ID,Test_Results")] Compound_Receipts compound_Receipts)
        {
            if (ModelState.IsValid)
            {
                db.Compound_Receipts.Add(compound_Receipts);
                db.SaveChanges();
                if (db.Work_Orders.Find(compound_Receipts.Work_Order_ID) != null)
                {
                    if (compound_Receipts.Date_Arrived != null)
                    {
                        IEnumerable <Customers> receipt =
                            db.Database.SqlQuery <Customers>("select distinct Customers.Customer_ID, customers.First_Name, Customers.Last_Name, customers.Street_Address, Customers.City, customers.State, Customers.Phone, Customers.Email, customers.Qualify_Discount, Customers.Password, customers.User_Role_ID " +
                                                             "FROM Customers " +
                                                             "inner join Work_Orders on " +
                                                             "Work_Orders.Customer_ID = Customers.Customer_ID " +
                                                             "inner join Compound_Receipts on " +
                                                             "Work_Orders.Work_Order_ID = Compound_Receipts.Work_Order_ID " +
                                                             "where Work_Orders.Work_Order_ID = " + compound_Receipts.Work_Order_ID);
                        Customers cust = db.Customers.FirstOrDefault(p => p.Email == User.Identity.Name);

                        List <Customers> listReceipt  = receipt.ToList();
                        Customers        firstReceipt = listReceipt.First();
                        var senderEmail   = new MailAddress("*****@*****.**", "Northwest Labs");
                        var receiverEmail = new MailAddress(firstReceipt.Email, "Receiver");
                        var password      = "******";
                        var body          = "Your Order has been received in Singapore on date: " + compound_Receipts.Date_Arrived + ". We will begin working on the tests as soon as possible.";
                        var smtp          = new SmtpClient
                        {
                            Host                  = "smtp.gmail.com",
                            Port                  = 587,
                            EnableSsl             = true,
                            DeliveryMethod        = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials           = new NetworkCredential(senderEmail.Address, password)
                        };
                        using (var mess = new MailMessage(senderEmail, receiverEmail)
                        {
                            Subject = "From Northwest Labs Singapore",
                            Body = "Our email if you have any questions: " + senderEmail.Address + "\n" + "Message: " + body
                        })
                        {
                            smtp.Send(mess);
                        }
                        {// stuff to change date of due for stuff
                            if (compound_Receipts.Date_Due != null)
                            {
                                IEnumerable <SortingworkOrders> date = db.SortingWorkOrders
                                                                       .Where(o => o.Work_Order_ID == compound_Receipts.Work_Order_ID);

                                List <SortingworkOrders> newDate = date.ToList();
                                foreach (SortingworkOrders ordere in newDate)
                                {
                                    ordere.Date_Due = compound_Receipts.Date_Due;
                                    // db.SortingWorkOrders.FirstOrDefault(p => p.Database_Number == lastOne.Database_Number).Date_Due = compound_Receipts.Date_Due;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }


                return(RedirectToAction("Index"));
            }
            ViewBag.error = "ERROR: Make sure your work order id is correct.";
            return(View(compound_Receipts));
        }
Exemplo n.º 35
0
        public virtual bool SendMail(string Hosting, string FromMail, string FromPassword, string toUser, string subject, string Body, string CC, string BCC)
        {
            try
            {
                if (_password != null && !string.IsNullOrEmpty(_password))
                {
                    FromPassword = _password;
                }

                if (Hosting == "yes")
                {
                    #region SENDMAIL FROM HOST

                    MailMessage message     = new MailMessage();
                    MailAddress fromAddress = new MailAddress(FromMail);
                    message.From       = fromAddress;
                    message.IsBodyHtml = true;

                    message.To.Add(toUser);

                    if (CC != null && !string.IsNullOrEmpty(CC))
                    {
                        message.CC.Add(CC);
                    }
                    if (BCC != null && !string.IsNullOrEmpty(BCC))
                    {
                        message.Bcc.Add(BCC);
                    }

                    message.Subject = subject;
                    message.Body    = Body;
                    SmtpClient client = new SmtpClient("localhost");
                    client.Timeout     = 30000;
                    client.Credentials = new System.Net.NetworkCredential(FromMail, FromPassword);
                    client.Send(message);


                    #endregion
                }
                else
                {
                    #region SEND MAIL FROM LOCAL SERVER

                    MailMessage mail       = new MailMessage();
                    SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                    mail.From = new MailAddress(FromMail);
                    mail.To.Add(toUser);

                    if (CC != null && !string.IsNullOrEmpty(CC))
                    {
                        mail.CC.Add(CC);
                    }
                    if (BCC != null && !string.IsNullOrEmpty(BCC))
                    {
                        mail.Bcc.Add(BCC);
                    }


                    mail.Subject  = subject;
                    mail.Priority = MailPriority.High;// added 9/9/2016
                    mail.Body     = Body;

                    mail.IsBodyHtml    = true;
                    SmtpServer.Port    = 587;
                    SmtpServer.Timeout = 30000;

                    SmtpServer.Credentials = new System.Net.NetworkCredential(FromMail, FromPassword);
                    SmtpServer.EnableSsl   = true;

                    //attachment
                    //foreach (var file in files)
                    //{
                    //    Attachment attachment = new Attachment(file.InputStream, file.FileName);
                    //    mail.Attachments.Add(attachment);
                    //}


                    SmtpServer.Send(mail);

                    #endregion
                }
                return(true);
            }
            catch (Exception ex)
            {
                string ms = ex.Message;
                //Console.WriteLine(ex.ToString());
            }
            return(false);
        }
Exemplo n.º 36
0
 public string SendEmail(MailAddress fromAddress, string subject, string message, MailAddress to, int?id = null, int?pid = null, List <MailAddress> cc = null)
 {
     return(SendEmail(fromAddress, subject, message, new[] { to }.ToList(), id, pid, cc));
 }
Exemplo n.º 37
0
 public void EmailFinanceInformation(MailAddress from, Person p, string subject, string body)
 {
     EmailFinanceInformation(from, p, null, subject, body);
 }
Exemplo n.º 38
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string    Errmsg         = "";
        string    FileRoute      = @"D:\Forwarder\FTP_Download\";
        string    tInitDirectory = @"D:\4GL\"; //原始目錄
        string    sql1           = "Select * From ForwarderData";
        string    sFileName      = "";
        string    sINV_Num       = "";
        ArrayList FtpList;

        FtpList = List("ftp://ftp.minaik.com.tw//ToMinaik//", "Agilitylogistics", "agi315708");

        System.Threading.Thread.Sleep(3000);

        foreach (string FileName in FtpList)
        {
            if (FileName.IndexOf(".xml") != -1)
            {
                //將目前FTP的XML抓下來
                Download("ftp://ftp.minaik.com.tw//ToMinaik//" + FileName, FileRoute, "Agilitylogistics", "agi315708");
                System.Threading.Thread.Sleep(3000);

                //FTP的XML抓下來後刪除FTP上XML檔案
                DeleteFileOnServer("ftp://ftp.minaik.com.tw//ToMinaik//" + FileName, "Agilitylogistics", "agi315708");
                System.Threading.Thread.Sleep(3000);
            }
        }


        // 設定檔案讀取位置...
        string searchPattern = "*";

        string        InitDirectory = @"D:\Forwarder\FTP_Download\"; //原始目錄
        ArrayList     MyFiles       = new ArrayList();
        DirectoryInfo di            = new DirectoryInfo(InitDirectory);

        GetFiles(di, searchPattern, ref MyFiles);

        foreach (string s in MyFiles)
        {
            try
            {
                //找到當天的檔名!
                if (s.IndexOf("_axmt610") != -1 || s.IndexOf("_axmt850") != -1)
                {
                    System.Diagnostics.Debug.Write(s);
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(s);

                    XmlNodeList PlantID          = xDoc.GetElementsByTagName("PlantID");
                    XmlNodeList ProgramID        = xDoc.GetElementsByTagName("ProgramID");
                    XmlNodeList INV_Num          = xDoc.GetElementsByTagName("oga27");
                    XmlNodeList Cdate            = xDoc.GetElementsByTagName("oga02");
                    XmlNodeList SHIPPING_to      = xDoc.GetElementsByTagName("addr");
                    XmlNodeList SHIPPING_No      = xDoc.GetElementsByTagName("oga31");
                    XmlNodeList SHIPPING_Dec     = xDoc.GetElementsByTagName("oah02");
                    XmlNodeList SHIPPING_Mode    = xDoc.GetElementsByTagName("oga43");
                    XmlNodeList SHIPPING_ModeDec = xDoc.GetElementsByTagName("ged02");
                    XmlNodeList FORWARDER_Num    = xDoc.GetElementsByTagName("ta_oga20");
                    XmlNodeList FORWARDER_Dec    = xDoc.GetElementsByTagName("pmc03");
                    XmlNodeList HawbNo           = xDoc.GetElementsByTagName("ta_oga26");
                    XmlNodeList FitNo            = xDoc.GetElementsByTagName("oga48");
                    XmlNodeList ETD   = xDoc.GetElementsByTagName("ta_oga22");
                    XmlNodeList ATD   = xDoc.GetElementsByTagName("ta_oga24");
                    XmlNodeList ETA   = xDoc.GetElementsByTagName("ta_oga21");
                    XmlNodeList ATAAS = xDoc.GetElementsByTagName("ta_oga23");
                    XmlNodeList ATAC  = xDoc.GetElementsByTagName("ta_oga25");

                    xDoc.Clone();

                    bool isChange = false;
                    bool isError  = false;

                    string isDiff   = "";
                    string IsStatus = "";

                    string TempID    = "";
                    string warstring = "";
                    string ERPKey    = "";


                    DateTime dtResult;
                    DateTime datetime;

                    string logETD       = "";
                    string logATD       = "";
                    string logETA       = "";
                    string logATAAS     = "";
                    string logATAC      = "";
                    string TempFileName = "";
                    string SHIPPINGDec  = "";

                    SmoothEnterprise.Database.DataSet rs = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenUpdate);
                    rs.Open("SELECT * FROM Forwarder WHERE INV_Num ='" + INV_Num[0].InnerXml + "'");
                    if (!rs.EOF)
                    {
                        TempFileName = rs["FileName"].ToString();
                        ERPKey       = rs["ERP_Key"].ToString();
                        IsStatus     = rs["IsStatus"].ToString();
                        TempID       = rs["id"].ToString();
                        SHIPPINGDec  = rs["SHIPPING_Dec"].ToString();

                        //  Hawbno Update ------------

                        if (HawbNo.Count != 0)
                        {
                            if (rs["HawbNo"].ToString() != HawbNo[0].InnerXml)
                            {
                                isChange     = true;
                                isDiff       = isDiff + " 提貨單號更動 (" + rs["HawbNo"].ToString() + " --> " + HawbNo[0].InnerXml + ")<BR/>";
                                rs["HawbNo"] = HawbNo[0].InnerXml;
                            }
                        }
                        else
                        {
                            isError   = true;
                            warstring = warstring + "提貨單號空值!!<BR/>";
                        }

                        //  Hawbno Update -----------



                        //  FitNo Update ----------

                        if (FitNo.Count != 0)
                        {
                            if (rs["FitNo"].ToString() != FitNo[0].InnerXml)
                            {
                                isChange    = true;
                                isDiff      = isDiff + "班機號碼/航班更動(" + rs["FitNo"].ToString() + " --> " + FitNo[0].InnerXml + ")<BR/>";
                                rs["FitNo"] = FitNo[0].InnerXml;
                            }
                        }
                        else
                        {
                            isError   = true;
                            warstring = warstring + "班機號碼/船名航次未填寫!!<BR/>";
                        }

                        //  FitNo Update ----------



                        //  ETD Update ----------
                        if (ETD.Count != 0)
                        {
                            // 記錄 ETD 時間
                            logETD = ETD[0].InnerXml;

                            if (DateTime.TryParse(ETD[0].InnerXml, out dtResult))
                            {
                                if (rs["ETD"] != System.DBNull.Value)
                                {
                                    datetime = Convert.ToDateTime(rs["ETD"].ToString());
                                    if (datetime.ToString("yyyy/MM/dd HH:mm") != ETD[0].InnerXml)
                                    {
                                        isChange  = true;
                                        isDiff    = isDiff + "ETD 更動(" + rs["ETD"].ToString() + " --> " + ETD[0].InnerXml + ")<BR/>";
                                        rs["ETD"] = ETD[0].InnerXml;
                                    }
                                }
                                else
                                {
                                    isChange  = true;
                                    isDiff    = isDiff + "ETD 更動( Null  --> " + ETD[0].InnerXml + ")<BR/>";
                                    rs["ETD"] = ETD[0].InnerXml;
                                }
                            }
                            else
                            {
                                isError   = true;
                                warstring = warstring + "ETD 時間格式異常!(" + ETD[0].InnerXml + ")<BR/>";
                            }
                        }
                        //  ETD Update ----------


                        //  ATD Update ----------
                        if (ATD.Count != 0)
                        {
                            // 記錄 ATD 時間
                            logATD = ATD[0].InnerXml;

                            if (DateTime.TryParse(ATD[0].InnerXml, out dtResult))
                            {
                                if (rs["ATD"] != System.DBNull.Value)
                                {
                                    datetime = Convert.ToDateTime(rs["ATD"].ToString());
                                    if (datetime.ToString("yyyy/MM/dd HH:mm") != ATD[0].InnerXml)
                                    {
                                        isChange  = true;
                                        isDiff    = isDiff + "ATD 更動(" + rs["ATD"].ToString() + " --> " + ATD[0].InnerXml + ")<BR/>";
                                        rs["ATD"] = ATD[0].InnerXml;
                                    }
                                }
                                else
                                {
                                    isChange  = true;
                                    isDiff    = isDiff + "ATD 更動( Null  --> " + ATD[0].InnerXml + ")<BR/>";
                                    rs["ATD"] = ATD[0].InnerXml;
                                }
                            }
                            else
                            {
                                isError   = true;
                                warstring = warstring + "ATD 時間格式異常!(" + ATD[0].InnerXml + ")<BR/>";
                            }
                        }
                        //  ATD Update ----------



                        //  ETA Update ----------
                        if (ETA.Count != 0)
                        {
                            // 記錄 ETA 時間
                            logETA = ETA[0].InnerXml;

                            if (DateTime.TryParse(ETA[0].InnerXml, out dtResult))
                            {
                                if (rs["ETA"] != System.DBNull.Value)
                                {
                                    datetime = Convert.ToDateTime(rs["ETA"].ToString());
                                    if (datetime.ToString("yyyy/MM/dd HH:mm") != ETA[0].InnerXml)
                                    {
                                        isChange  = true;
                                        isDiff    = isDiff + "ETA 更動(" + rs["ETA"].ToString() + " --> " + ETA[0].InnerXml + ")<BR/>";
                                        rs["ETA"] = ETA[0].InnerXml;
                                    }
                                }
                                else
                                {
                                    isChange  = true;
                                    isDiff    = isDiff + "ETA 更動( Null  --> " + ETA[0].InnerXml + ")<BR/>";
                                    rs["ETA"] = ETA[0].InnerXml;
                                }
                            }
                            else
                            {
                                isError   = true;
                                warstring = warstring + "ETA 時間格式異常!(" + ETA[0].InnerXml + ")<BR/>";
                            }
                        }
                        //  ETA Update ----------


                        //  ATAAS Update ----------
                        if (ATAAS.Count != 0)
                        {
                            // 記錄 ATAAS 時間
                            logATAAS = ATAAS[0].InnerXml;


                            if (DateTime.TryParse(ATAAS[0].InnerXml, out dtResult))
                            {
                                if (rs["ATAAS"] != System.DBNull.Value)
                                {
                                    datetime = Convert.ToDateTime(rs["ATAAS"].ToString());
                                    if (datetime.ToString("yyyy/MM/dd HH:mm") != ATAAS[0].InnerXml)
                                    {
                                        isChange    = true;
                                        isDiff      = isDiff + "ATAAS 更動(" + rs["ATAAS"].ToString() + " --> " + ATAAS[0].InnerXml + ")<BR/>";
                                        rs["ATAAS"] = ATAAS[0].InnerXml;
                                    }
                                }
                                else
                                {
                                    isChange    = true;
                                    isDiff      = isDiff + "ATAAS 更動( Null --> " + ATAAS[0].InnerXml + ")<BR/>";
                                    rs["ATAAS"] = ATAAS[0].InnerXml;
                                }
                            }
                            else
                            {
                                isError   = true;
                                warstring = warstring + "ATAAS 時間格式異常!(" + ATAAS[0].InnerXml + ")<BR/>";
                            }
                        }
                        //  ATAAS Update ----------



                        //  ATAC Update ----------
                        if (ATAC.Count != 0)
                        {
                            // 記錄 ATAC 時間
                            logATAC = ATAC[0].InnerXml;


                            if (DateTime.TryParse(ATAC[0].InnerXml, out dtResult))
                            {
                                if (rs["ATAC"] != System.DBNull.Value)
                                {
                                    datetime = Convert.ToDateTime(rs["ATAC"].ToString());
                                    if (datetime.ToString("yyyy/MM/dd HH:mm") != ATAC[0].InnerXml)
                                    {
                                        isChange   = true;
                                        isDiff     = isDiff + "ATAC 更動(" + rs["ATAC"].ToString() + " --> " + ATAC[0].InnerXml + ")<BR/>";
                                        rs["ATAC"] = ATAC[0].InnerXml;
                                    }
                                }
                                else
                                {
                                    isChange   = true;
                                    isDiff     = isDiff + "ATAC 更動( Null  --> " + ATAC[0].InnerXml + ")<BR/>";
                                    rs["ATAC"] = ATAC[0].InnerXml;
                                }
                            }
                            else
                            {
                                isError   = true;
                                warstring = warstring + "ATAC 時間格式異常!(" + ATAC[0].InnerXml + ")<BR/>";
                            }
                        }
                        //  ATAC Update ----------


                        if (isChange)
                        {
                            rs["Udate"]    = System.DateTime.Now.ToString();
                            rs["IsStatus"] = "isSend";
                            rs.Update();
                        }


                        rs.Close();
                    }
                    else
                    {
                        isError = true;


                        //發現資料庫沒此資料 OR 已審核完畢
                        Errmsg = "您好:" + "<br>" +
                                 "<br>" +
                                 "時間:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "<br><br>" +
                                 "出通單號:" + ERPKey + "<br>" +
                                 "發票編號:" + INV_Num[0].InnerXml + "<br>" +
                                 "錯誤情形:查無此單據資料,無法更新!!<br>" +
                                 "<br>" +
                                 "錯誤檔案:" + s + "<br>" +
                                 "廠商名稱:" + FORWARDER_Dec[0].InnerXml + "<br><br>" +
                                 "因本信件為系統自動發送,請勿直接以此郵件回覆。";

                        rs.Close();
                    }


                    if (isChange)
                    {
                        this.FlowClient1.RequestURL = "/Shipping/ForwarderEdit?id=" + TempID;
                        this.FlowClient1.StopRequest(this.FlowClient1.RequestURL);

                        this.FlowClient1.Flow.DefaultNode().ReviewerURL = "/Shipping/ForwarderView.aspx";
                        this.FlowClient1.RequestURL = "/Shipping/ForwarderEdit.aspx?id=" + TempID;
                        this.FlowClient1.AddParameter("USER", "1d933141-e015-47fe-a6f2-846231264ac0");
                        this.FlowClient1.SendRequest(new System.Guid("1d933141-e015-47fe-a6f2-846231264ac0"));

                        MailAddress from    = new MailAddress("*****@*****.**", "Forwarder(審核通知-" + ERPKey + ")");
                        MailAddress to      = new MailAddress("*****@*****.**");
                        MailAddress bcc     = new MailAddress("*****@*****.**");
                        MailMessage message = new MailMessage(from, to);
                        message.Bcc.Add(bcc);
                        message.Subject = "Forwarder(Agi審核通知)";
                        Errmsg          = "您好:" + "<br>" +
                                          "<br>" +
                                          "時間:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "<br><br>" +
                                          "出通單號:" + ERPKey + "<br>" +
                                          "發票編號:" + INV_Num[0].InnerXml + "<br>" +
                                          "價格條件:" + SHIPPING_No[0].InnerXml + "<br>" +
                                          "價格描述:" + SHIPPINGDec + "<br>" +
                                          "Forwarder 價格條件異常~<br>" + warstring +
                                          "<br>" +
                                          "錯誤檔案:" + s + "<br>" +
                                          "廠商名稱:" + FORWARDER_Dec[0].InnerXml + "<br><br>" +
                                          "===================== 明  細  異  動 =====================<br>" + isDiff +
                                          "====================================================<br>" +
                                          "點選下列連結進行審核!!<br>" +
                                          "<a href=http://eip.minaik.com.tw/Shipping/ForwarderView.aspx?ID=" + TempID + ">http://eip.minaik.com.tw/Shipping/ForwarderView.aspx?ID=" + TempID + "</a><br>" +
                                          "因本信件為系統自動發送,請勿直接以此郵件回覆。";
                        message.IsBodyHtml = true;
                        message.Body       = Errmsg;
                        SmtpClient client = new SmtpClient("192.168.0.12");
                        client.Send(message);

                        isError = false;
                    }


                    if (isError)
                    {
                        MailAddress from    = new MailAddress("*****@*****.**", "Forwarder(資料錯誤)");
                        MailAddress to      = new MailAddress("*****@*****.**");
                        MailMessage message = new MailMessage(from, to);
                        message.Subject = "Forwarder(資料錯誤)";

                        if (Errmsg == "")
                        {
                            Errmsg = "您好:" + "<br>" +
                                     "<br>" +
                                     "時間:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "<br><br>" +
                                     "出通單號:" + ERPKey + "<br>" +
                                     "發票編號:" + INV_Num[0].InnerXml + "<br>" +
                                     "價格條件:" + SHIPPING_No[0].InnerXml + "<br>" +
                                     "價格描述:" + SHIPPINGDec + "<br>" +
                                     "<br>" +
                                     "檔案名稱:" + s + "<br>" +
                                     "廠商名稱:" + FORWARDER_Dec[0].InnerXml + "<br><br>" +
                                     "================== 錯  誤  明  細 ==================<br>" + warstring +
                                     "====================================================<br>" +
                                     "因本信件為系統自動發送,請勿直接以此郵件回覆。";
                        }
                        message.IsBodyHtml = true;
                        message.Body       = Errmsg;
                        SmtpClient client = new SmtpClient("192.168.0.12");
                        client.Send(message);
                    }


                    string ReFileName = "";

                    if (System.IO.File.Exists(s.Replace("\\FTP_Download\\", "\\FTP_XML\\")))      //判斷在 FTP_BXML 資料夾裡, 檔案是否存在
                    {
                        File.Delete(s.Replace("\\FTP_Download\\", "\\FTP_XML\\"));                //存在的話先刪除該檔案再存入新檔案

                        ReFileName = DateTime.Now.ToString("yyyy-MM-dd_HHmmss");
                        File.Move(s, s.Replace("\\FTP_Download\\", "\\FTP_XML\\").Replace(".xml", "_" + ReFileName + ".xml"));
                    }
                    else
                    {
                        ReFileName = DateTime.Now.ToString("yyyy-MM-dd_HHmmss");
                        File.Move(s, s.Replace("\\FTP_Download\\", "\\FTP_XML\\").Replace(".xml", "_" + ReFileName + ".xml"));
                    }

                    SmoothEnterprise.Database.DataSet rs2 = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenUpdate);
                    rs2.Open("SELECT * FROM Forwarder_log WHERE INV_Num ='" + INV_Num[0].InnerXml + "'");
                    if (rs2.EOF)
                    {
                        Response.Write(TempFileName.Replace(".xml", "_" + ReFileName + ".xml"));
                        rs2.Add();
                        rs2["INV_Num"]      = INV_Num[0].InnerXml;
                        rs2["logETD"]       = logETD;
                        rs2["logATD"]       = logATD;
                        rs2["logETA"]       = logETA;
                        rs2["logATAAS"]     = logATAAS;
                        rs2["logATAC"]      = logATAC;
                        rs2["DataFileName"] = TempFileName.Replace(".xml", "_" + ReFileName + ".xml");
                        rs2["DataUpdate"]   = DateTime.Now.ToString("yyyy-MM-dd HH:mm");;
                        rs2.Update();
                    }
                    else
                    {
                        Response.Write(TempFileName.Replace(".xml", "_" + ReFileName + ".xml"));
                        rs2["INV_Num"]      = INV_Num[0].InnerXml;
                        rs2["logETD"]       = logETD;
                        rs2["logATD"]       = logATD;
                        rs2["logETA"]       = logETA;
                        rs2["logATAAS"]     = logATAAS;
                        rs2["logATAC"]      = logATAC;
                        rs2["DataFileName"] = TempFileName.Replace(".xml", "_" + ReFileName + ".xml");
                        rs2["DataUpdate"]   = DateTime.Now.ToString("yyyy-MM-dd HH:mm");;
                        rs2.Update();
                    }
                    xDoc.Clone();
                    rs2.Close();
                }
            }
            catch (Exception ex)
            {
                MailAddress from    = new MailAddress("*****@*****.**", "Forwarder(錯誤訊息)");
                MailAddress to      = new MailAddress("*****@*****.**");
                MailMessage message = new MailMessage(from, to);
                message.Subject = "Forwarder(錯誤訊息)";
                string ques = "";
                ques = "您好:" + "<br>" +
                       "<br>" +
                       "Forwarder 系統發生錯誤~<br>" +
                       "<br>" +
                       "錯誤檔案:" + s + "<br>" +
                       "錯誤訊息:" + ex + "<br><br>" +
                       "因本信件為系統自動發送,請勿直接以此郵件回覆。";
                message.IsBodyHtml = true;
                message.Body       = ques;
                SmtpClient client = new SmtpClient("192.168.0.12");
                client.Send(message);
            }
        }
    }
Exemplo n.º 39
0
        /// <summary>
        /// Send email(s) over SendGrid’s v3 Web API
        /// </summary>
        /// <param name="personalizations">The personalizations.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="contents">The contents.</param>
        /// <param name="from">From.</param>
        /// <param name="replyTo">The reply to.</param>
        /// <param name="attachments">The attachments.</param>
        /// <param name="templateId">The template identifier.</param>
        /// <param name="sections">The sections.</param>
        /// <param name="headers">The headers.</param>
        /// <param name="categories">The categories.</param>
        /// <param name="customArgs">The custom arguments.</param>
        /// <param name="sendAt">The send at.</param>
        /// <param name="batchId">The batch identifier.</param>
        /// <param name="unsubscribeOptions">The unsubscribe options.</param>
        /// <param name="ipPoolName">Name of the ip pool.</param>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="trackingSettings">The tracking settings.</param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        /// The message id.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">Too many recipients</exception>
        /// <exception cref="Exception">Email exceeds the size limit</exception>
        public async Task <string> SendAsync(
            IEnumerable <MailPersonalization> personalizations,
            string subject,
            IEnumerable <MailContent> contents,
            MailAddress from,
            MailAddress replyTo = null,
            IEnumerable <Attachment> attachments = null,
            string templateId = null,
            IEnumerable <KeyValuePair <string, string> > sections = null,
            IEnumerable <KeyValuePair <string, string> > headers  = null,
            IEnumerable <string> categories = null,
            IEnumerable <KeyValuePair <string, string> > customArgs = null,
            DateTime?sendAt = null,
            string batchId  = null,
            UnsubscribeOptions unsubscribeOptions = null,
            string ipPoolName                   = null,
            MailSettings mailSettings           = null,
            TrackingSettings trackingSettings   = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (personalizations == null || !personalizations.Any())
            {
                throw new ArgumentNullException(nameof(personalizations));
            }

            // The total number of recipients must be less than 1000. This includes all recipients defined within the to, cc, and bcc parameters, across each object that you include in the personalizations array.
            var numberOfRecipients = personalizations.Sum(p => p?.To?.Count(r => r != null) ?? 0);

            numberOfRecipients += personalizations.Sum(p => p?.Cc?.Count(r => r != null) ?? 0);
            numberOfRecipients += personalizations.Sum(p => p?.Bcc?.Count(r => r != null) ?? 0);
            if (numberOfRecipients >= 1000)
            {
                throw new ArgumentOutOfRangeException("The total number of recipients must be less than 1000");
            }

            var data = new JObject();

            if (from != null)
            {
                data.Add("from", JToken.FromObject(from));
            }
            if (replyTo != null)
            {
                data.Add("reply_to", JToken.FromObject(replyTo));
            }
            if (!string.IsNullOrEmpty(subject))
            {
                data.Add("subject", subject);
            }
            if (contents != null && contents.Any())
            {
                data.Add("content", JToken.FromObject(contents.ToArray()));
            }
            if (attachments != null && attachments.Any())
            {
                data.Add("attachments", JToken.FromObject(attachments.ToArray()));
            }
            if (!string.IsNullOrEmpty(templateId))
            {
                data.Add("template_id", templateId);
            }
            if (categories != null && categories.Any())
            {
                data.Add("categories", JToken.FromObject(categories.ToArray()));
            }
            if (sendAt.HasValue)
            {
                data.Add("send_at", sendAt.Value.ToUnixTime());
            }
            if (!string.IsNullOrEmpty(batchId))
            {
                data.Add("batch_id", batchId);
            }
            if (unsubscribeOptions != null)
            {
                data.Add("asm", JToken.FromObject(unsubscribeOptions));
            }
            if (!string.IsNullOrEmpty(ipPoolName))
            {
                data.Add("ip_pool_name", ipPoolName);
            }
            if (mailSettings != null)
            {
                data.Add("mail_settings", JToken.FromObject(mailSettings));
            }
            if (trackingSettings != null)
            {
                data.Add("tracking_settings", JToken.FromObject(trackingSettings));
            }

            // It's important to make a copy of the personalizations to ensure we don't modify the original array
            var personalizationsCopy = personalizations.ToArray();

            foreach (var personalization in personalizationsCopy)
            {
                personalization.To  = EnsureRecipientsNamesAreQuoted(personalization.To);
                personalization.Cc  = EnsureRecipientsNamesAreQuoted(personalization.Cc);
                personalization.Bcc = EnsureRecipientsNamesAreQuoted(personalization.Bcc);
            }

            data.Add("personalizations", JToken.FromObject(personalizationsCopy));

            if (sections != null && sections.Any())
            {
                var sctns = new JObject();
                foreach (var section in sections)
                {
                    sctns.Add(section.Key, section.Value);
                }

                data.Add("sections", sctns);
            }

            if (headers != null && headers.Any())
            {
                var hdrs = new JObject();
                foreach (var header in headers)
                {
                    hdrs.Add(header.Key, header.Value);
                }

                data.Add("headers", hdrs);
            }

            if (customArgs != null && customArgs.Any())
            {
                var args = new JObject();
                foreach (var customArg in customArgs)
                {
                    args.Add(customArg.Key, customArg.Value);
                }

                data.Add("custom_args", args);
            }

            // Sendgrid does not allow emails that exceed 30MB
            var contentSize = JsonConvert.SerializeObject(data, Formatting.None).Length;

            if (contentSize > MAX_EMAIL_SIZE)
            {
                throw new Exception("Email exceeds the size limit");
            }

            var response = await _client
                           .PostAsync($"{_endpoint}/send")
                           .WithJsonBody(data)
                           .WithCancellationToken(cancellationToken)
                           .AsResponse()
                           .ConfigureAwait(false);

            var messageId = (string)null;

            if (response.Message.Headers.Contains("X-Message-Id"))
            {
                messageId = response.Message.Headers.GetValues("X-Message-Id").FirstOrDefault();
            }

            return(messageId);
        }
Exemplo n.º 40
0
 private void ValidateEmailReplacementCodes(CMSDataContext db, string emailText, MailAddress fromAddress)
 {
     var er = new EmailReplacements(db, emailText, fromAddress);
     er.DoReplacements(db, db.LoadPersonById(Util.UserPeopleId ?? 0));
 }
Exemplo n.º 41
0
        public string SendGridMsg(MailAddress from, string subject, string message, List <MailAddress> to, int?id, int?pid, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];

            string fromDomain, apiKey;

            if (ShouldUseCustomEmailDomain)
            {
                fromDomain = CustomFromDomain;
                apiKey     = CustomSendGridApiKey;
            }
            else
            {
                fromDomain = DefaultFromDomain;
                apiKey     = DefaultSendGridApiKey;
            }

            if (from == null)
            {
                from = Util.FirstAddress(senderrorsto);
            }

            var mail = new Mail
            {
                From    = new Email(fromDomain, from.DisplayName),
                Subject = subject,
                ReplyTo = new Email(from.Address, from.DisplayName)
            };
            var pe = new Personalization();

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    pe.AddTo(new Email(ma.Address, ma.DisplayName));
                }
            }

            if (cc?.Count > 0)
            {
                string cclist = string.Join(",", cc);
                if (!cc.Any(vv => vv.Address.Equal(from.Address)))
                {
                    cclist = $"{from.Address},{cclist}";
                }
                mail.ReplyTo = new Email(cclist);
            }

            pe.AddHeader(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            pe.AddHeader(XBvcms, XBvcmsHeader(id, pid));

            mail.AddPersonalization(pe);

            if (pe.Tos.Count == 0 && pe.Tos.Any(tt => tt.Address.EndsWith("@nowhere.name")))
            {
                return(null);
            }
            var badEmailLink = "";

            if (pe.Tos.Count == 0)
            {
                pe.AddTo(new Email(from.Address, from.DisplayName));
                pe.AddTo(new Email(Util.FirstAddress(senderrorsto).Address));
                mail.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink  = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var text  = regex.Replace(message, string.Empty);
            var html  = badEmailLink + message + CcMessage(cc);

            mail.AddContent(new MContent("text/plain", text));
            mail.AddContent(new MContent("text/html", html));

            var reqBody = mail.Get();

            using (var wc = new WebClient())
            {
                wc.Headers.Add("Authorization", $"Bearer {apiKey}");
                wc.Headers.Add("Content-Type", "application/json");
                wc.UploadString("https://api.sendgrid.com/v3/mail/send", reqBody);
            }
            return(fromDomain);
        }
        public void SendEmailCancelled()
        {
            try
            {
                var streamReader =
                    new StreamReader(
                        HostingEnvironment.MapPath("/Modules/Sails/Admin/EmailTemplate/CancelledBookingNotify.txt"));
                var content = streamReader.ReadToEnd();
                var appPath = string.Format("{0}://{1}{2}{3}",
                                            Request.Url.Scheme,
                                            Request.Url.Host,
                                            Request.Url.Port == 80
                                     ? string.Empty
                                     : ":" + Request.Url.Port,
                                            Request.ApplicationPath);
                content = content.Replace("{link}",
                                          appPath + "Modules/Sails/Admin/BookingView.aspx?NodeId=1&SectionId=15&bi=" + Booking.Id);
                content = content.Replace("{bookingcode}", Booking.BookingIdOS);
                content = content.Replace("{agency}", Booking.Agency.Name);
                content = content.Replace("{startdate}", Booking.StartDate.ToString("dd/MM/yyyy"));
                content = content.Replace("{trip}", Booking.Trip.Name);
                content = content.Replace("{cruise}", Booking.Cruise.Name);
                content = content.Replace("{customernumber}", Booking.Pax.ToString());
                content = content.Replace("{roomnumber}", Booking.BookingRooms.Count.ToString());
                content = content.Replace("{submiter}", UserIdentity.FullName);
                content = content.Replace("{reason}", Booking.CancelledReason);
                MailAddress fromAddress = new MailAddress("*****@*****.**", "Hệ Thống MO OrientalSails");
                MailMessage message     = new MailMessage();
                message.From = fromAddress;
                message.To.Add("*****@*****.**");
                if (Booking.CreatedBy != null)
                {
                    if (Booking.CreatedBy.Email != null)
                    {
                        if (Booking.CreatedBy.Email != "*****@*****.**")
                        {
                            message.To.Add(Booking.CreatedBy.Email);
                        }
                    }
                }

                if (Booking.ModifiedBy != null)
                {
                    if (Booking.ModifiedBy.Email != null)
                    {
                        if (Booking.ModifiedBy.Email != Booking.CreatedBy.Email)
                        {
                            if (Booking.ModifiedBy.Email != "*****@*****.**")
                            {
                                message.To.Add(Booking.ModifiedBy.Email);
                            }
                        }
                    }
                }

                message.To.Add("*****@*****.**");
                message.To.Add("*****@*****.**");
                message.Subject      = "Thông báo hủy booking";
                message.IsBodyHtml   = true;
                message.BodyEncoding = Encoding.UTF8;
                message.Body         = content;
                message.Bcc.Add("*****@*****.**");
                EmailService.SendMessage(message);
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 43
0
 public EmailQueue CreateQueue(MailAddress From, string subject, string body, DateTime?schedule, int tagId, bool publicViewable, bool?ccParents = null, string cclist = null)
 {
     return(CreateQueue(Util.UserPeopleId, From, subject, body, schedule, tagId, publicViewable, ccParents: ccParents, cclist: cclist));
 }
Exemplo n.º 44
0
    protected Boolean Send_Email_Client(String sp_token, String sp_email, String sp_firstname, String sp_lastname)
    {
        var emailSent    = true;
        var toName       = (sp_firstname + " " + sp_lastname).Trim();
        var emailAddress = new MailAddress(sp_email, toName);

        var emailUser = System.Configuration.ConfigurationManager.AppSettings["mail1User"];
        var emailName = System.Configuration.ConfigurationManager.AppSettings["mail1Name"];
        var emailPass = System.Configuration.ConfigurationManager.AppSettings["mail1Pass"];

        var    senderEmail    = new MailAddress(emailUser, emailName);
        string senderPassword = emailPass;

        string emailSubject = "Application - Password Recovery";
        var    emailFile    = "Password_Recovery_Email.html";
        var    emailPath    = @"~/App_Data/Emails/";

        System.IO.StreamReader rdr = new System.IO.StreamReader(Server.MapPath(emailPath + emailFile));
        var htmlBody = rdr.ReadToEnd();

        rdr.Close();
        rdr.Dispose();

        // Update html variables
        htmlBody = htmlBody.Replace("{username}", sp_email);
        htmlBody = htmlBody.Replace("{token}", sp_token);
        htmlBody = htmlBody.Replace("{host}", Request.Url.Host);

        var smtp = new SmtpClient
        {
            Host                  = "smtp.gmail.com",
            Port                  = 587,
            EnableSsl             = true,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials           = new NetworkCredential(senderEmail.Address, senderPassword)
        };

        var message = new MailMessage(senderEmail, emailAddress);

        message.Subject    = emailSubject;
        message.IsBodyHtml = true;
        message.Body       = htmlBody;

        try
        {
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            emailSent       = false;
            lblMessage.Text = "Error sending email";

            lblMessage.Text += String.Format("<table class='table_error'>"
                                             + "<tr><td>Error<td/><td>{0}</td></tr>"
                                             + "<tr><td>Message<td/><td>{1}</td></tr>"
                                             + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                             + "<tr><td>Source<td/><td>{3}</td></tr>"
                                             + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                             + "<tr><td>Data<td/><td>{5}</td></tr>"
                                             + "</table>"
                                             , "Email Sender"    //0
                                             , ex.Message        //1
                                             , ex.StackTrace     //2
                                             , ex.Source         //3
                                             , ex.InnerException //4
                                             , ex.Data           //5
                                             , ex.HelpLink
                                             , ex.TargetSite
                                             );
        }

        return(emailSent);
    }
Exemplo n.º 45
0
        public EmailQueue CreateQueue(int?queuedBy, MailAddress from, string subject, string body, DateTime?schedule, int tagId, bool publicViewable, int?goerSupporterId = null, bool?ccParents = null, string cclist = null)
        {
            var tag = TagById(tagId);

            if (tag == null)
            {
                return(null);
            }

            var emailqueue = new EmailQueue
            {
                Queued        = Util.Now,
                FromAddr      = from.Address,
                FromName      = from.DisplayName,
                Subject       = subject,
                Body          = body,
                SendWhen      = schedule,
                QueuedBy      = queuedBy,
                Transactional = false,
                PublicX       = publicViewable,
                CCParents     = ccParents,
                CClist        = cclist,
                Testing       = Util.IsInRoleEmailTest,
                ReadyToSend   = false, // wait until all individual emailqueueto records are created.
            };

            EmailQueues.InsertOnSubmit(emailqueue);
            SubmitChanges();

            if (body.Contains("http://publiclink", ignoreCase: true))
            {
                var link = ServerLink("/EmailView/" + emailqueue.Id);
                var re   = new Regex("http://publiclink",
                                     RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase);
                emailqueue.Body = re.Replace(body, link);
            }

            var q = tag.People(this);

            IQueryable <int> q2 = null;

            if (emailqueue.CCParents == true)
            {
                q2 = from p in q.Distinct()
                     where (p.EmailAddress ?? "") != "" ||
                     (p.Family.HeadOfHousehold.EmailAddress ?? "") != "" ||
                     (p.Family.HeadOfHouseholdSpouse.EmailAddress ?? "") != ""
                     where (p.SendEmailAddress1 ?? true) ||
                     (p.SendEmailAddress2 ?? false) ||
                     (p.Family.HeadOfHousehold.SendEmailAddress1 ?? false) ||
                     (p.Family.HeadOfHousehold.SendEmailAddress2 ?? false) ||
                     (p.Family.HeadOfHouseholdSpouse.SendEmailAddress1 ?? false) ||
                     (p.Family.HeadOfHouseholdSpouse.SendEmailAddress2 ?? false)
                     where p.EmailOptOuts.All(oo => oo.FromEmail != emailqueue.FromAddr)
                     orderby p.PeopleId
                     select p.PeopleId;
            }
            else
            {
                q2 = from p in q.Distinct()
                     where p.EmailAddress != null
                     where p.EmailAddress != ""
                     where (p.SendEmailAddress1 ?? true) || (p.SendEmailAddress2 ?? false)
                     where p.EmailOptOuts.All(oo => oo.FromEmail != emailqueue.FromAddr)
                     orderby p.PeopleId
                     select p.PeopleId;
            }

            foreach (var pid in q2)
            {
                emailqueue.EmailQueueTos.Add(new EmailQueueTo
                {
                    PeopleId      = pid,
                    OrgId         = Util2.CurrentOrgId,
                    Guid          = Guid.NewGuid(),
                    GoerSupportId = goerSupporterId,
                });
            }
            emailqueue.ReadyToSend = true;
            SubmitChanges();
            return(emailqueue);
        }
Exemplo n.º 46
0
        public void SendEmail(string asunto, string plantilla, string remitente, string nombreRemitente, string receptor, object model = null, List <string> rutasArchivos = null, String copiacarbon = null, String copiaOculta = null)
        {
            try
            {
                using (var SecurePassword = new SecureString())
                {
                    copiaOculta = copiaOculta ?? String.Empty;
                    copiacarbon = copiacarbon ?? String.Empty;
                    Array.ForEach(ConfigurationManager.AppSettings["ClaveCorreoSistema"].ToArray(), SecurePassword.AppendChar);

                    TemplateRender templateRender = new TemplateRender(Parent);

                    using (var smtpClient = new SmtpClient
                    {
                        Host = "mail.afari.pe", //Host Afari
                        Port = 25,              //Port Afari
                        EnableSsl = true,
                        Timeout = 60000,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(ConfigurationManager.AppSettings["CorreoSistema"], SecurePassword)
                    })
                    {
                        var LstReceptores = receptor.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        LstReceptores = ConvertHelpers.RemoveDuplicates(LstReceptores);
                        //foreach (var r in LstReceptores)
                        //{
                        MailAddress from = new MailAddress(remitente, nombreRemitente);
                        //MailAddress to = new MailAddress(r);//receptor);
                        MailAddress to = new MailAddress(LstReceptores[0]);
                        using (var mailMessage = new MailMessage(from, to))
                        {
                            mailMessage.From = from;
                            //if (plantilla != "info")
                            //{
                            for (int i = 1; i < LstReceptores.Count(); i++)
                            {
                                mailMessage.To.Add(LstReceptores[i]);
                            }
                            //}
                            mailMessage.Body       = templateRender.Render(plantilla, model);
                            mailMessage.IsBodyHtml = true;
                            mailMessage.Subject    = asunto;
                            mailMessage.Sender     = from;

                            if (plantilla != "info")
                            {
                                mailMessage.Bcc.Add(new MailAddress(remitente));
                                var LstReceptoresOcultos = copiaOculta.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var item in LstReceptoresOcultos)
                                {
                                    mailMessage.Bcc.Add(item);
                                }
                            }

                            if (!String.IsNullOrEmpty(copiacarbon) && copiacarbon.Length > 5)
                            {
                                var ccAddress = copiacarbon.Split(',');
                                foreach (var ccA in ccAddress)
                                {
                                    if (!String.IsNullOrEmpty(ccA))
                                    {
                                        if (ccA.Contains("@afari.pe"))
                                        {
                                            mailMessage.CC.Add(new MailAddress(ccA));
                                        }
                                        else
                                        {
                                            if (plantilla != "info")
                                            {
                                                mailMessage.CC.Add(new MailAddress(ccA));
                                            }
                                            else
                                            {
                                                mailMessage.CC.Add(new MailAddress("cc_" + ccA));
                                            }
                                        }
                                    }
                                }
                            }

                            if (rutasArchivos != null)
                            {
                                foreach (var archivo in rutasArchivos)
                                {
                                    var rutaAlArchivo = archivo;
                                    var data          = new Attachment(rutaAlArchivo, MediaTypeNames.Application.Octet);
                                    var disposition   = data.ContentDisposition;
                                    disposition.FileName         = Path.GetFileNameWithoutExtension(archivo) + Path.GetExtension(archivo);
                                    disposition.CreationDate     = DateTime.Now;
                                    disposition.ModificationDate = DateTime.Now;
                                    disposition.ReadDate         = DateTime.Now;

                                    if (data != null)
                                    {
                                        mailMessage.Attachments.Add(data);
                                    }
                                }
                            }
                            ServicePointManager.ServerCertificateValidationCallback =
                                delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                         X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
                            { return(true); };

                            smtpClient.Send(mailMessage);
                        }
                        //}
                    }
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 47
0
        private void SendEmail(MailAddress fromAddress, string subject, string message, List <MailAddress> to, EmailQueueTo eqto, List <MailAddress> cc = null)
        {
            var domain = SendEmail(fromAddress, subject, message, to, eqto.Id, eqto.PeopleId, cc);

            eqto.DomainFrom = domain;
        }
Exemplo n.º 48
0
        public ActionResult Resume(ResumeVM fillResume)
        {
            if (ModelState.IsValid)
            {
                fillResume.Result = "";
                fillResume.Submit();

                var section = "";
                if (fillResume.s1)
                {
                    section = section + "Web специалисты ";
                }
                if (fillResume.s2)
                {
                    section = section + ";" + "Администраторы сетей ";
                }
                if (fillResume.s3)
                {
                    section = section + ";" + "Программисты ";
                }
                if (fillResume.s4)
                {
                    section = section + ";" + "Бухгалтеры ";
                }
                if (fillResume.s5)
                {
                    section = section + ";" + "Верстальщики ";
                }
                if (fillResume.s6)
                {
                    section = section + ";" + "Дизайнеры ";
                }
                if (fillResume.s7)
                {
                    section = section + ";" + "Менеджеры ";
                }
                if (fillResume.s8)
                {
                    section = section + ";" + "Операторы ПК ";
                }
                if (fillResume.s9)
                {
                    section = section + ";" + "Проектировщики ";
                }
                if (fillResume.s10)
                {
                    section = section + ";" + "Специалисты по тех обслуживанию ПК ";
                }
                if (fillResume.s11)
                {
                    section = section + ";" + "Логисты (Склад и грузоперевозки) ";
                }
                if (fillResume.s12)
                {
                    section = section + ";" + "Секретари ";
                }
                if (fillResume.s13)
                {
                    section = section + ";" + "Разное ";
                }

                var user    = (User)HttpContext.Session["CurrentUserSessionKey"];
                var resumes = new List <Resume>();

                var resume =
                    new Resume
                {
                    UserID     = user.UserID,
                    FirstName  = fillResume.YourName,
                    SecondName = fillResume.YourPatronymic,
                    LastName   = fillResume.YourSurname,
                    Age        = Convert.ToInt16(fillResume.YourAge),
                    Sex        = fillResume.YourSex,
                    Education  = fillResume.YourEducation,
                    Position   = fillResume.YourPosition,
                    Sections   = section,
                    Experience = fillResume.YourExperience,
                    Profit     = Convert.ToInt32(fillResume.YourProfit),
                    Currency   = fillResume.YourCurrency,
                    City       = fillResume.YourCity,
                    Metro      = fillResume.YourMetro,
                    Period     = fillResume.YourPeriod,
                    Email      = fillResume.YourEmail,
                    Phone      = fillResume.YourTelHome + ";" + fillResume.YourTelJob + ";" + fillResume.YourTelMob,
                    IsActive   = true,
                    UpdateDate = DateTime.Now
                };

                resumes.Add(resume);

                foreach (var res in resumes)
                {
                    ResumeService.Insert(res);
                }

                ResumeService.SubmitChanges();

                var message = new StringBuilder();

                message.Append("<p>");
                message.Append("Основная информация");
                message.Append("<br/>");
                message.AppendFormat("Имя {0} ", fillResume.YourName);
                message.Append("<br/>");
                message.AppendFormat("Отчество {0} ", fillResume.YourPatronymic);
                message.Append("<br/>");
                message.AppendFormat("фамилия {0} ", fillResume.YourSurname);
                message.Append("<br/>");
                message.AppendFormat("Пол {0} ", fillResume.YourSex);
                message.Append("<br/>");
                message.AppendFormat("Возраст {0} ", fillResume.YourAge);
                message.Append("<br/>");

                message.AppendFormat("Образование {0} ", fillResume.YourEducation);
                message.Append("<br/>");
                message.AppendFormat("Желаемая должность {0} ", fillResume.YourPosition);
                message.Append("<br/>");

                message.Append("Раздел ");
                if (fillResume.s1)
                {
                    message.Append("Веб-технологии ");
                }
                if (fillResume.s2)
                {
                    message.Append("Системное администрирование ");
                }
                if (fillResume.s3)
                {
                    message.Append("Программирование ");
                }
                if (fillResume.s4)
                {
                    message.Append("Бухгалтерия / Финансы ");
                }
                if (fillResume.s5)
                {
                    message.Append("Дизайн, графика, верстка, 3D ");
                }
                if (fillResume.s6)
                {
                    message.Append("Кадры/управление персоналом ");
                }
                if (fillResume.s7)
                {
                    message.Append("Административный персонал ");
                }
                if (fillResume.s8)
                {
                    message.Append("Проектирование ");
                }
                if (fillResume.s9)
                {
                    message.Append("Техническое обслуживание ПК, HelpDesk ");
                }
                if (fillResume.s10)
                {
                    message.Append("Складское хозяйство / Логистика / ВЭД ");
                }
                if (fillResume.s11)
                {
                    message.Append("Продажи / Закупки ");
                }
                if (fillResume.s12)
                {
                    message.Append("Информационная безопасность ");
                }
                if (fillResume.s13)
                {
                    message.Append("Маркетинг / Реклама / PR ");
                }
                if (fillResume.s14)
                {
                    message.Append("Разное ");
                }
                message.Append("<br/>");

                message.AppendFormat("Опыт работы {0} ", fillResume.YourExperience);
                message.Append("<br/>");
                message.AppendFormat("Заработная плата {0} ", fillResume.YourProfit);
                message.Append(fillResume.YourCurrency);
                message.Append(" в месяц ");
                message.Append("<br/>");
                message.AppendFormat("Город {0} ", fillResume.YourCity);
                message.Append("<br/>");
                message.AppendFormat("Ближайшая станция метро {0} ", fillResume.YourMetro);
                message.Append("<br/>");
                message.AppendFormat("Срок публикации резюме {0} ", fillResume.YourPeriod);
                message.Append("<br/>");
                message.Append("Контактная информация ");
                message.Append("<br/>");
                message.AppendFormat("E-mail {0} ", fillResume.YourEmail);
                message.Append("<br/>");
                message.Append("Телефон: ");
                message.Append("<br/>");
                message.AppendFormat("Домашний {0} ", fillResume.YourTelHome);
                message.Append("<br/>");
                message.AppendFormat("Служебный {0} ", fillResume.YourTelJob);
                message.Append("<br/>");
                message.AppendFormat("Мобильный {0} ", fillResume.YourTelMob);
                message.Append("<br/>");
                message.Append("</p>");

                MailAddress from   = new MailAddress("*****@*****.**");
                MailAddress to     = new MailAddress("*****@*****.**");
                UploadFile  upFile = new UploadFile();
                if (Session["UploadFileForResume"] != null)
                {
                    var userfile = (IEnumerable <HttpPostedFileBase>)Session["UploadFileForResume"];
                    var fileName = "";
                    var index    = userfile.First().FileName.LastIndexOf("\\");
                    if (index > 0)
                    {
                        fileName = userfile.First().FileName.Substring(index);
                    }
                    else
                    {
                        fileName = userfile.First().FileName;
                    }

                    upFile.ContentLength = userfile.First().ContentLength;
                    upFile.Name          = fileName;
                    upFile.Stream        = userfile.First().InputStream;
                }
                MailService.SendForResume(from, to, message.ToString(), "Резюме", upFile);


                return(View(fillResume));
            }
            else
            {
                var model = new ResumeVM();
                model.Result = "";
                return(View(model));
            }
        }
Exemplo n.º 49
0
        public string SendGridMsg(MailAddress from, string subject, string message, List <MailAddress> to, int?id, int?pid, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];

            string fromDomain, apiKey;

            if (ShouldUseCustomEmailDomain)
            {
                fromDomain = CustomFromDomain;
                apiKey     = CustomSendGridApiKey;
            }
            else
            {
                fromDomain = DefaultFromDomain;
                apiKey     = DefaultSendGridApiKey;
            }
            var client = new SendGridClient(apiKey);

            if (from == null)
            {
                from = Util.FirstAddress(senderrorsto);
            }

            var mail = new SendGridMessage()
            {
                From             = new EmailAddress(fromDomain, from.DisplayName),
                Subject          = subject,
                ReplyTo          = new EmailAddress(from.Address, from.DisplayName),
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            var pe = new Personalization();

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    mail.AddTo(new EmailAddress(ma.Address, ma.DisplayName));
                }
            }

            if (cc?.Count > 0)
            {
                string cclist = string.Join(",", cc);
                if (!cc.Any(vv => vv.Address.Equal(from.Address)))
                {
                    cclist = $"{from.Address},{cclist}";
                }
                mail.ReplyTo = new EmailAddress(cclist);
            }

            pe.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            pe.Headers.Add(XBvcms, XBvcmsHeader(id, pid));

            mail.Personalizations.Add(pe);

            if (pe.Tos.Count == 0 && pe.Tos.Any(tt => tt.Email.EndsWith("@nowhere.name")))
            {
                return(null);
            }
            var badEmailLink = "";

            if (pe.Tos.Count == 0)
            {
                pe.Tos.Add(new EmailAddress(from.Address, from.DisplayName));
                pe.Tos.Add(new EmailAddress(Util.FirstAddress(senderrorsto).Address));
                mail.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink  = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            mail.PlainTextContent = regex.Replace(message, string.Empty);
            mail.HtmlContent      = badEmailLink + message + CcMessage(cc);

            var response = client.SendEmailAsync(mail);

            return(fromDomain);
        }
Exemplo n.º 50
0
        //Method to send mail with mail parameters (dynamic (have to set for every mail))
        private static void SendMailDo(MailAddress[] eMailTo, string subject, string body, int retryCounter, MailAddress eMailFrom_special, string smtpClient_special, string password_special, int?port_special,
                                       bool highPriority, MailAddress[] eMailToCC, MailAddress[] eMailToBCC, Attachment[] eMailAttachment)
        {
            //Declaration of Variables
            int tryCounter = 1;
            int port_special_intern;

            #region settings

            mail         = new MailMessage();
            mail.Subject = subject;
            mail.Body    = body;

            if (eMailTo == null)
            {
                foreach (MailAddress element in MAD.MadConf.conf.MAIL_DEFAULT)//to get all eMailIds from incoming Array
                {
                    mail.To.Add(element);
                }
            }

            else
            {
                foreach (MailAddress element in eMailTo)//to get all eMailIds from incoming Array
                {
                    mail.To.Add(element);
                }
            }

            if (eMailToCC != null)
            {
                foreach (MailAddress element in eMailToCC)
                {
                    mail.CC.Add(element);
                }
            }

            if (eMailToBCC != null)
            {
                foreach (MailAddress element in eMailToBCC)
                {
                    mail.Bcc.Add(element);
                }
            }

            if (eMailAttachment != null)
            {
                foreach (Attachment element in eMailAttachment)
                {
                    mail.Attachments.Add(element);
                }
            }

            if (highPriority == true)
            {
                mail.Priority = MailPriority.High;
            }

            if (eMailFrom_special == null)
            {
                eMailFrom_special = MAD.MadConf.conf.SMTP_USER;
                mail.From         = eMailFrom_special;
            }

            else
            {
                mail.From = eMailFrom_special;
            }

            if (smtpClient_special == null)
            {
                smtpClient_special = MAD.MadConf.conf.SMTP_SERVER;
            }

            if (password_special == null)
            {
                password_special = MAD.MadConf.conf.SMTP_PASS;
            }

            if (port_special == null)
            {
                port_special = MAD.MadConf.conf.SMTP_PORT;
            }

            port_special_intern = port_special.GetValueOrDefault();



            #endregion

            #region Authentification and sending process
            for (; tryCounter <= retryCounter; tryCounter++)//to retry because shit happens
            {
                try
                {
                    eMailSendingAttempt = tryCounter + ".Attempt";
                    Logger.Log(eMailSendingAttempt, Logger.MessageType.INFORM);
                    SmtpClient client = new SmtpClient();
                    client.Port        = port_special_intern;
                    client.Host        = smtpClient_special;
                    client.Credentials = new NetworkCredential(eMailFrom_special.ToString(), password_special);
                    client.EnableSsl   = true;

                    ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
                    { return(true); };
                    client.Send(mail);
                    eMailSendingSucceed = "(" + tryCounter + ".Attempt) Success Sir";
                    Logger.Log(eMailSendingSucceed, Logger.MessageType.INFORM);
                    client.Dispose();
                    break;
                }

                catch (Exception ex)
                {
                    eMailSendingFailed = "(" + tryCounter + ".Attempt) Sending mail failed Sir becuase: " + ex.Message;
                    Logger.Log(eMailSendingFailed, Logger.MessageType.ERROR);//ex gives a report_intern of problems
                    Logger.ForceWriteToLog();
                    try
                    {
                        client.Dispose();
                        continue;
                    }
                    catch
                    {
                        continue;
                    }
                }
            }

            #endregion
        }
Exemplo n.º 51
0
        public string SendEmailMasivoVisita(string asunto, string plantilla, string remitente, string nombreRemitente, string receptor, ViewModel.Templates.infoViewModel model = null, String copiacarbon = null, String copiaOculta = null, VisitaCorretaje visita = null)
        {
            try
            {
                using (var SecurePassword = new SecureString())
                {
                    copiaOculta = copiaOculta ?? String.Empty;
                    copiacarbon = copiacarbon ?? String.Empty;
                    Array.ForEach(ConfigurationManager.AppSettings["ClaveCorreoSistema"].ToArray(), SecurePassword.AppendChar);

                    TemplateRender templateRender = new TemplateRender(Parent);

                    using (var smtpClient = new SmtpClient
                    {
                        Host = "mail.afari.pe", //Host Afari
                        Port = 25,              //Port Afari
                        EnableSsl = true,
                        Timeout = 60000,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(remitente, SecurePassword)
                    })
                    {
                        var LstReceptores = receptor.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        LstReceptores = ConvertHelpers.RemoveDuplicates(LstReceptores);
                        //foreach (var r in LstReceptores)
                        //{
                        MailAddress from = new MailAddress(remitente, nombreRemitente);
                        //MailAddress to = new MailAddress(r);//receptor);
                        MailAddress to = new MailAddress(LstReceptores[0]);
                        using (var mailMessage = new MailMessage(from, to))
                        {
                            mailMessage.From = from;
                            //if (plantilla != "info")
                            //{
                            for (int i = 1; i < LstReceptores.Count(); i++)
                            {
                                mailMessage.To.Add(LstReceptores[i]);
                            }
                            //}
                            mailMessage.Body += $"<!DOCTYPE html>";
                            mailMessage.Body += $"<html xmlns='http://www.w3.org/1999/xhtml'>";
                            mailMessage.Body += $"<head>";
                            mailMessage.Body += $"    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>";
                            mailMessage.Body += $"    <meta content='width=device-width, initial-scale=1.0' name='viewport'>";
                            mailMessage.Body += $"    <title>@model.Titulo</title>";
                            mailMessage.Body += $"</head>";
                            mailMessage.Body += $"<body>";
                            mailMessage.Body += $"    <div style='font-family:Calibri;font-size:15px'>";
                            mailMessage.Body += $"        " + (model.Mensaje.Replace(" ", "&nbsp;").Replace("\n", "<br/>").ToString());
                            mailMessage.Body += $"    </div>";
                            mailMessage.Body += $"    <br />";
                            mailMessage.Body += $"    <p style='font-family:Calibri;font-size:15px'>    Saludos cordiales,</p>";
                            mailMessage.Body += $"    <br />";
                            if (!String.IsNullOrEmpty(model.Firma) && model.Firma.Length > 1)
                            {
                                mailMessage.Body += $"        <img src='http://afari.pe/intranet/Resources/Files/" + model.Firma + "' />";
                            }
                            mailMessage.Body += $"</body>";
                            mailMessage.Body += $"</html>";

                            mailMessage.IsBodyHtml = true;
                            mailMessage.Subject    = asunto;
                            mailMessage.Sender     = from;

                            if (plantilla != "info")
                            {
                                mailMessage.Bcc.Add(new MailAddress(remitente));
                                var LstReceptoresOcultos = copiaOculta.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var item in LstReceptoresOcultos)
                                {
                                    mailMessage.Bcc.Add(item);
                                }
                            }

                            if (!String.IsNullOrEmpty(copiacarbon) && copiacarbon.Length > 5)
                            {
                                var ccAddress = copiacarbon.Split(',');
                                foreach (var ccA in ccAddress)
                                {
                                    if (!String.IsNullOrEmpty(ccA))
                                    {
                                        if (ccA.Contains("@afari.pe"))
                                        {
                                            mailMessage.CC.Add(new MailAddress(ccA));
                                        }
                                        else
                                        {
                                            if (plantilla != "info")
                                            {
                                                mailMessage.CC.Add(new MailAddress(ccA));
                                            }
                                            else
                                            {
                                                mailMessage.CC.Add(new MailAddress("cc_" + ccA));
                                            }
                                        }
                                    }
                                }
                            }

                            Stream rutasArchivo = getConstanciaVisita(visita.VisitaCorretajeId);
                            if (rutasArchivo != null)
                            {
                                var data        = new Attachment(rutasArchivo, MediaTypeNames.Application.Octet);
                                var disposition = data.ContentDisposition;
                                disposition.FileName         = "Constancia_Visita_" + visita.Fecha.ToString("dd/MM/yyyy") + "_" + visita.NombreCliente + ".pdf";
                                disposition.CreationDate     = DateTime.Now;
                                disposition.ModificationDate = DateTime.Now;
                                disposition.ReadDate         = DateTime.Now;

                                if (data != null)
                                {
                                    mailMessage.Attachments.Add(data);
                                }
                            }
                            ServicePointManager.ServerCertificateValidationCallback =
                                delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                         X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
                            { return(true); };

                            smtpClient.Send(mailMessage);
                        }
                        //}
                    }
                }
            }

            catch (Exception ex)
            {
                return(ex.Message + (ex.InnerException != null ? ex.InnerException.Message : String.Empty));
            }
            return(String.Empty);
        }
Exemplo n.º 52
0
 public void SetToAddress(string toMail)
 {
     // 호출
     this.toAddress = new MailAddress(toMail);
 }
Exemplo n.º 53
0
        // Function used for actually sending emails from HomeServer.
        public static void Send(string To, string Subject, string Body, string FileName)
        {
            // Open new client and set properties.
            mailSent = false;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);

            client.Credentials = new NetworkCredential("gatechsmarthouse", "SmartHouse4012");
            client.EnableSsl   = true;

            // Send from Smart House email address.
            MailAddress from = new MailAddress("*****@*****.**", "Smart House", System.Text.Encoding.UTF8);

            // Send to Smart House user email address.
            MailAddress to = new MailAddress(To, "Smart House User", System.Text.Encoding.UTF8);

            // Open new mail message.
            MailMessage message = new MailMessage(from, to);

            message.Body            = Body;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = Subject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;

            // If a filename was given, then attach the file.
            if (FileName != null)
            {
                if (File.Exists(FileName))
                {
                    // Create  the file attachment for this e-mail message.
                    Attachment data = new Attachment(FileName, MediaTypeNames.Application.Octet);

                    // Add time stamp information for the file.
                    ContentDisposition disposition = data.ContentDisposition;
                    disposition.CreationDate     = System.IO.File.GetCreationTime(FileName);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(FileName);
                    disposition.ReadDate         = System.IO.File.GetLastAccessTime(FileName);

                    // Add the file attachment to this e-mail message.
                    message.Attachments.Add(data);
                }
                else
                {
                    Console.WriteLine("The file with filename : {0} does not exist. Please check the filename and try again.", FileName);
                }
            }

            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

            // The userState can be any object that allows your callback
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = Subject;

            client.SendAsync(message, userState);
            //Console.WriteLine("Sending message...");

            /*
             * string answer = Console.ReadLine();
             *
             * // If the user canceled the send, and mail hasn't been sent yet,
             * // then cancel the pending operation.
             * if (answer.StartsWith("c") && mailSent == false)
             * {
             *  client.SendAsyncCancel();
             * }
             *
             * // Clean up.
             * message.Dispose();
             */
            while (mailSent == false)
            {
            }
        }
Exemplo n.º 54
0
        public void SendMail(int msgType, Article article)
        {
            if (article.Author == null)
            {
                article.Author = db.Users.First(u => u.Id == article.AuthorId);
            }
            if (article.Reviewer == null)
            {
                article.Reviewer = db.Users.First(u => u.Id == article.ReviewerId);
            }
            String      typeSubject = "";
            String      content     = "";
            MailAddress toAddress   = new MailAddress(article.Author.Email, article.Author.Username);

            switch (msgType)
            {
            //Reviewer has new Article to review
            case 0:
                typeSubject = "------!NEW Article to review!------";
                content     = "A new article has been given to you to review";
                toAddress   = new MailAddress(article.Reviewer.Email, article.Reviewer.Username);
                break;

            //Writer's Article is accpeted and published
            case 1:
                typeSubject = "------Article APPROVED------";
                content     = "Your article has been aproved";
                break;

            //Writer's Article is not approved
            case 2:
                typeSubject = "------Article NOT APPROVED------";
                content     = "Your article has not been aproved";
                break;
            }
            try
            {
                var           fromAddress  = new MailAddress("*****@*****.**", "NotificationBot");
                const string  fromPassword = "******";
                const string  subject      = "NEW NOTIFICATION";
                StringBuilder sb           = new StringBuilder();
                sb.Append(typeSubject);
                sb.Append(Environment.NewLine);
                sb.Append(content);
                sb.Append(Environment.NewLine);
                sb.Append("Article Name: " + article.Title);

                string body = sb.ToString();

                var smtp = new SmtpClient
                {
                    Host                  = "smtp.gmail.com",
                    Port                  = 587,
                    EnableSsl             = true,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    smtp.Send(message);
                }
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 55
0
        public PatientProfilePage(string doctor, string personName, string personLastname, string personParent, DateTime personBirthDate, string personTelephone, string personGender, string personLivingCity, string personBirthCity, string personPin, MailAddress personEmail)
        {
            InitializeComponent();
            this.DataContext = this;
            patient          = MainWindow.patient;
            doctors          = new ObservableCollection <string>();

            patient.name         = personName;
            patient.parentName   = personParent;
            patient.lastname     = personLastname;
            patient.pin          = personPin;
            patient.birth        = personBirthDate;
            patient.living_city  = personLivingCity;
            patient.birth_city   = personBirthCity;
            patient.chosenDoctor = doctor;
            patient.email        = personEmail;
            patient.gender       = personGender;
            patient.number       = personTelephone;

            Notifications notifi = new Notifications();

            notifications = notifi.notifications;

            doctors.Add("dr Zoran Radovanovic");
            doctors.Add("dr Goran Stevanovic");
            doctors.Add("dr Jovan Prodanov");
            doctors.Add("dr Jelena Klasnjar");
            doctors.Add("dr Miodrag Djukic");
            doctors.Add("dr Petar Petrovic");
            doctors.Add("dr Legenda Nestorovic");

            chosenDoctor.Text = patient.chosenDoctor;
            name.Text         = patient.name;
            parent.Text       = patient.parentName;
            lastname.Text     = patient.lastname;
            pin.Text          = patient.pin;
            tel.Text          = patient.number;
            gender.Text       = patient.gender;
            dtp.SelectedDate  = patient.birth.Date;
            livingCity.Text   = patient.living_city;
            birthCity.Text    = patient.birth_city;
            email.Text        = patient.email.ToString();
        }
Exemplo n.º 56
0
        //---------------------------------------
        //
        // ICertificateResolver
        //
        //---------------------------------------
        /// <summary>
        /// Calls GetCertificates, catches exceptions
        /// Returns null if exceptions
        /// </summary>
        /// <param name="resolver">certificate resolver</param>
        /// <param name="address">Retrieve certificates for this address</param>
        /// <returns>
        /// A <see cref="System.Security.Cryptography.X509Certificates.X509Certificate2Collection"/> or null if there are no matches.
        /// </returns>
        public static X509Certificate2Collection SafeGetCertificates(this ICertificateResolver resolver, MailAddress address)
        {
            try
            {
                return(resolver.GetCertificates(address));
            }
            catch
            {
            }

            return(null);
        }
Exemplo n.º 57
0
        protected void FlowFeedback1_FlowStop(object sender, SmoothEnterprise.Flowwork.UI.WebControl.FlowStopEventArgs e)
        {
            if (e.ResultType == SmoothEnterprise.Flowwork.Control.ReviewResultType.Complete)
            {
                try
                {
                    string sqlstr = "";
                    sqlstr = "SELECT * FROM EngineeringTest_head where id='" + Request.QueryString["id"] + "'";
                    SmoothEnterprise.Database.DataSet ds;
                    ds = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenUpdate);
                    ds.Open(sqlstr);

                    if (!ds.EOF)
                    {
                        ds["STATUS"] = "完成審核";
                        ds.Update();

                        SmoothEnterprise.Database.DataSet rss = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                        rss.Open("select add_user , email,mail,name from EngineeringTest_head a  left join dguser b on a.add_user=b.id where a.id='" + Request.QueryString["id"] + "'   ");
                        if (!rss.EOF)
                        {
                            #region 寄給申請人完成的mail

                            ArrayList email_list = new ArrayList(); //email list
                            email_list.Add(rss["email"].ToString());

                            #endregion

                            #region 寄給通知者

                            String[] s = rss["mail"].ToString().Split(';');
                            foreach (string bb in s)
                            {
                                email_list.Add(bb.ToString());
                                //Response.Write(bb.ToString());
                            }

                            #endregion

                            #region Send email


                            String ques;

                            MailAddress from = new MailAddress("*****@*****.**", "ePortal(員工入口網站)");
                            //MailAddress to = new MailAddress(i);

                            MailAddress bcc     = new MailAddress("*****@*****.**");
                            MailMessage message = new MailMessage("*****@*****.**", rss["email"].ToString());
                            foreach (string i in email_list)
                            {
                                if (!string.IsNullOrEmpty(i))
                                {
                                    message.To.Add(i);
                                }
                            }

                            DateTime de = Convert.ToDateTime(this.FIELD_expect_date.Text);
                            ques = "您好:" + "<br>" +
                                   "<br>" +
                                   "EIP工程試作單系統已完成審核, 詳細資料如下:" + "<br>" +
                                   "<br>" +
                                   "單號 : " + this.no.Text + "<br>" +
                                   "申請日期 : " + de.ToString("yyyy/MM/dd") + "<br>" +
                                   "申請內容 : " + "<a href=\"http://eip.minaik.com.tw/EngineeringTest/EngineeringTestView.aspx?id=" + Request.QueryString["id"] + "\" >至EIP工程試作單系統查看</a>" +
                                   "<br>" +
                                   "如您想了解更多有關員工入口網站的資訊請點選以下連結進入" + "<br>" +
                                   "<a href=\"http://eip.minaik.com.tw/\">員工入口網站</a>" + "<br>" +
                                   "感謝您對員工入口網站的支持與愛護,<font Color='red'>。因本信件為系統自動發送,請勿直接以此郵件回覆。</font>";

                            message.Subject = "EIP工程試作單號 - " + this.no.Text + " 成品料號-" + this.cima01.Text + "己完成審核";

                            message.IsBodyHtml = true;
                            message.Body       = ques;

                            SmtpClient client = new SmtpClient("192.168.0.12");

                            client.Send(message);



                            #endregion

                            if (this.cima01.Text.Substring(1, 1) == "9") //料號的開頭如果是”9”的時候要寄出去信件並新增至模具試模試作系統中
                            {
                                #region 寫入NPI_TryoutFeedback
                                EIPSysSha eip = new EIPSysSha();
                                SmoothEnterprise.Database.DataSet rss2 = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                                string NPI_TryoutFeedbackSN            = eip.GetNewSn("N301", DateTime.Now.Year.ToString().Substring(2, 2) + DateTime.Now.Month.ToString("00"), "EIPB", "PAPDETAIL");
                                string Guidstring = Guid.NewGuid().ToString();
                                string sqlcommand = "INSERT INTO EIPB.dbo.NPI_TryoutFeedback " +
                                                    "          (rowno , " +
                                                    "           SN , " +
                                                    "           PNO , " +
                                                    "           PRODUCTION_NAME ," +
                                                    "           Drawing , " +
                                                    "           NPI ,  " +
                                                    "           VER , " +
                                                    "           QUARYTI ," +
                                                    "           samples," +
                                                    "           ORDERS," +
                                                    "           Explanation," +
                                                    "           NOTE, " +
                                                    "           Measured_datetime ," +
                                                    "           initdate ," +
                                                    "           inituid)  " +
                                                    "   VALUES('" + Guidstring + "'," +
                                                    "          '" + NPI_TryoutFeedbackSN + "'," +
                                                    "          '" + this.cima01.Text + "'," +
                                                    "          '" + this.cima02.Text + "'," +
                                                    "          '" + this.cima03.Text + "'," +
                                                    "          '" + rss["add_user"].ToString() + "'," +
                                                    "          '" + this.rev.Text + "'," +
                                                    "          " + this.oduction_amount.Text + "," +
                                                    "          " + this.delivers_amount.Text + "," +
                                                    "          '" + this.order_no.Text + "'," +
                                                    "          '" + this.oduction_explain.Text + "'," +
                                                    "          '" + this.remark.Text + "'," +
                                                    "          '" + this.FIELD_expect_date.Text + "' , " +
                                                    "          SYSDATETIME()," +
                                                    "          '" + rss["add_user"].ToString() + "')";
                                //throw new Exception(sqlcommand);
                                rss2.ExecuteNonQuery(sqlcommand);
                                #endregion

                                #region 寫入NPI的預設MailGrid
                                InsertIntoMailGrid(Guidstring);
                                #endregion

                                #region 寄出模具試模計劃的EMail
                                SendMail(email_list, Guidstring, NPI_TryoutFeedbackSN);
                                #endregion
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message + ex.StackTrace);
                    //showError(ex.Message);
                }
            }

            if (e.ResultType == SmoothEnterprise.Flowwork.Control.ReviewResultType.Terminate ||
                e.ResultType == SmoothEnterprise.Flowwork.Control.ReviewResultType.Return)
            {
                //try
                //{
                string sqlstr = "";
                sqlstr = "SELECT * FROM EngineeringTest_head where id='" + Request.QueryString["id"] + "'";
                SmoothEnterprise.Database.DataSet ds;
                ds = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenUpdate);
                ds.Open(sqlstr);

                if (!ds.EOF)
                {
                    ds["STATUS"] = "退回";
                    ds.Update();

                    SmoothEnterprise.Database.DataSet rss = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                    rss.Open("select add_user bid,email,name from EngineeringTest_head a  left join dguser b on a.add_user=b.id where a.id='" + Request.QueryString["id"] + "'   ");
                    if (!rss.EOF)
                    {
                        #region 寄給申請人退回的mail

                        ArrayList email_list = new ArrayList();  //email list
                        email_list.Add(rss["email"].ToString());

                        #region 如資材單位已簽核過, 也給生管單位一份

                        SmoothEnterprise.Database.DataSet rsa = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                        rsa.Open("select * from dgflowqueue where text='資材單位' and qseq='1' and reviewresult is not null and   requesturl like '%" + Request.QueryString["id"] + "'");
                        if (!rsa.EOF)
                        {
                            SmoothEnterprise.Database.DataSet rsb = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                            rsb.Open("select email from dguser where id='" + this.FIELD_pmcsend.Text + "'");
                            if (!rsb.EOF)
                            {
                                email_list.Add(rsb["email"].ToString());
                            }
                        }


                        #endregion

                        #endregion

                        #region Send email

                        foreach (string i in email_list)
                        {
                            String ques;

                            MailAddress from = new MailAddress("*****@*****.**", "ePortal(員工入口網站)");
                            MailAddress to   = new MailAddress(i);

                            MailAddress bcc = new MailAddress("*****@*****.**");

                            MailMessage message = new MailMessage(from, to);
                            DateTime    de      = Convert.ToDateTime(this.FIELD_expect_date.Text);
                            ques = "您好:" + "<br>" +
                                   "<br>" +
                                   "EIP工程試作單系統已被退回, 詳細資料如下:" + "<br>" +
                                   "<br>" +
                                   "單號 : " + this.no.Text + "<br>" +
                                   "申請日期 : " + de.ToString("yyyy/MM/dd") + "<br>" +
                                   "申請內容 : " + "<a href=\"http://eip.minaik.com.tw/EngineeringTest/EngineeringTestView.aspx?id=" + Request.QueryString["id"] + "\" >至EIP工程試作單系統查看</a>" +
                                   "<br>" +
                                   "如您想了解更多有關員工入口網站的資訊請點選以下連結進入" + "<br>" +
                                   "<a href=\"http://eip.minaik.com.tw/\">員工入口網站</a>" + "<br>" +
                                   "感謝您對員工入口網站的支持與愛護,<font Color='red'>。因本信件為系統自動發送,請勿直接以此郵件回覆。</font>";

                            message.Subject = "EIP工程試作單號 - " + this.no.Text + " 成品料號-" + this.cima01.Text + "己被退回";

                            message.IsBodyHtml = true;
                            message.Body       = ques;

                            SmtpClient client = new SmtpClient("192.168.0.12");

                            client.Send(message);
                        }

                        #endregion
                    }
                }

                //}
                //catch
                //{
                //    Response.Write("有問題");
                //}
            }
        }
Exemplo n.º 58
0
        protected void Page_PreRender(object sender, System.EventArgs e)
        {
            //發信測試------------------------------------------

            //Response.Write(this.CurrentUser.LogonID.ToString());
            if (_NotifyReview)
            {
                SmoothEnterprise.Database.DataSet rss = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead);
                rss.Open("select top 1 REPLACE(requesturl,'EDIT','VIEW') requesturl,b.name name,email,b.id bid from dgflowqueue a left join dguser b on revieweruid=b.id where requesturl like '%" + Request.QueryString["id"] + "'  AND reviewdate IS NULL AND qseq is not null ");
                if (!rss.EOF)
                {
                    ArrayList email_list = new ArrayList(); //email list


                    email_list.Add(rss["name"].ToString() + '#' + rss["email"].ToString());

                    #region 代理人
                    SmoothEnterprise.Database.DataSet rs2 = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenUpdate);
                    rs2.Open(" SELECT b.name name,email FROM dguserdeputy a left join dguser b on a.deputyuid=b.id left join dgflow c on a.sid=c.id  " +
                             " where  a.uid='" + rss["bid"].ToString() + "'  " +
                             " and  " +
                             " ((a.sid is null and  sdate < GETDATE() and edate is null) or " +
                             " (c.typename like 'ERP_FLOW%' and sdate < GETDATE() and edate is null) or " +
                             " (c.typename like 'ERP_FLOW%' and sdate < GETDATE() and edate > GETDATE()) or " +
                             "  a.sid is null and sdate < GETDATE() and edate  > GETDATE())   group by b.name,email ");
                    while (!rs2.EOF)
                    {
                        //MyLibrary_AXMT610 Backsend = new MyLibrary_AXMT610();
                        email_list.Add(rs2["name"].ToString() + '#' + rs2["email"].ToString());
                        rs2.MoveNext();
                    }
                    rs2.Close();

                    #endregion

                    foreach (string i in email_list)
                    {
                        //Response.Write( i + "<br>");
                        //Response.Write(i.Split('#')[0] + "<br>");  //人員姓名
                        //Response.Write(i.Split('#')[1] + "<br>");  //人員email

                        String ques;

                        MailAddress from = new MailAddress("*****@*****.**", "ePortal(員工入口網站)");
                        MailAddress to   = new MailAddress(i.Split('#')[1]);

                        MailAddress bcc     = new MailAddress("*****@*****.**");
                        MailAddress bccrage = new MailAddress("*****@*****.**");

                        MailMessage message = new MailMessage(from, to);
                        message.Bcc.Add(bcc);
                        message.Bcc.Add(bccrage);
                        DateTime de = Convert.ToDateTime(this.FIELD_expect_date.Text);
                        ques = i.Split('#')[0] + " 您好:" + "<br>" +
                               "<br>" +
                               "EIP工程試作單系統現有一筆,正等待您的處理:" + "<br>" +
                               "<br>" +
                               "單號 : " + this.no.Text + "<br>" +
                               "申請日期 : " + de.ToString("yyyy/MM/dd") + "<br>" +
                               "申請內容 : " + "<a href=\"http://eip.minaik.com.tw/EngineeringTest/EngineeringTestView.aspx?id=" + Request.QueryString["id"] + "\" >至EIP工程試作單系統審核</a>" +
                               "<br>" +
                               "如您想了解更多有關員工入口網站的資訊請點選以下連結進入" + "<br>" +
                               "<a href=\"http://eip.minaik.com.tw/\">員工入口網站</a>" + "<br>" +
                               "感謝您對員工入口網站的支持與愛護,<font Color='red'>。因本信件為系統自動發送,請勿直接以此郵件回覆。</font>";

                        message.Subject = "EIP工程試作單號 - " + this.no.Text + " 成品料號-" + this.cima01.Text + "正在待您審核中";

                        message.IsBodyHtml = true;
                        message.Body       = ques;

                        SmtpClient client = new SmtpClient("192.168.0.12");

                        client.Send(message);
                    }
                }
            }
            //DBTransfer actsql3 = new DBTransfer();
            //actsql3.RunIUSql("insert into  misbuffer2(caption)values('ann信最外裡面" + this.FIELD_pmk01.Text + "')");
        }
Exemplo n.º 59
0
    public void Send_Email(object sender, EventArgs e)
    {
        SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CIT386-DB"].ConnectionString);

        sqlConn.Open();

        string[] stuName = new string[2];
        stuName = toHidden.Value.Split(' ');

        SqlCommand mailCmd = sqlConn.CreateCommand();

        mailCmd.CommandText = "SELECT email FROM student WHERE firstName = '" + stuName[0] + "' AND lastName = '" + stuName[1] + "'";
        string stuEmail = (string)mailCmd.ExecuteScalar();

        int advisorID = (int)Session["advisorID"];

        mailCmd.CommandText = "SELECT email FROM advisor WHERE accountID = '" + advisorID + "'";
        string advEmail = (string)mailCmd.ExecuteScalar();

        mailCmd.CommandText = "SELECT firstName FROM advisor WHERE accountID = '" + advisorID + "'";
        string advFname = (string)mailCmd.ExecuteScalar();

        mailCmd.CommandText = "SELECT lastName FROM advisor WHERE accountID = '" + advisorID + "'";
        string advLname = (string)mailCmd.ExecuteScalar();
        string advName  = advFname + " " + advLname;

        sqlConn.Close();

        var sysLogin = "******";
        var sysPass  = "******";

        var sysAddress      = new MailAddress(advEmail, advName);
        var receiverAddress = new MailAddress(stuEmail, stuEmail);

        string mailBody = "";

        mailBody += "<html>";
        mailBody += "	<head>";
        mailBody += "		<style>";
        mailBody += "			#footer{ font-size: 14px; width: 100%; text-align: center; margin: 30px; margin-top: 50px; margin-bottom: 0px; padding-top: 30px; padding-bottom: 30px; background-color: lightgrey; border-radius: 10px; }";
        mailBody += "		</style>";
        mailBody += "	</head>";
        mailBody += "	<body>";
        mailBody += mailMessage.Text;
        mailBody += "		<p id=\"footer\">This email was sent by <strong>";
        mailBody += advName + "</strong> via PennCollegeAdvising.com. To reply to " + advFname + " directly, ";
        mailBody += "contact <strong>" + advEmail + "</strong>.</p>";
        mailBody += "	</body>";
        mailBody += "</html>";

        var smtp = new SmtpClient
        {
            Host                  = "smtp.gmail.com", //gmail example
            Port                  = 587,
            EnableSsl             = true,
            DeliveryMethod        = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials           = new System.Net.NetworkCredential(sysLogin, sysPass)
        };

        var message = new MailMessage(sysAddress, receiverAddress)
        {
            From       = sysAddress,
            Subject    = subject.Text,
            IsBodyHtml = true,
            Body       = mailBody
        };

        using (message)
        {
            smtp.Send(message);
        }
    }
Exemplo n.º 60
0
        public Task SendAsync(IdentityMessage message)
        {
            // return configSendGridasync(message);
            // convert IdentityMessage to a MailMessage
            var email =
                new MailMessage(new MailAddress("*****@*****.**", "GWA"),
                                new MailAddress(message.Destination))
            {
                Subject    = message.Subject,
                Body       = message.Body,
                IsBodyHtml = true
            };
            var client = new SmtpClient();

            client.SendCompleted += (s, e) => {
                client.Dispose();
            };
            NetworkCredential basicCredential =
                new NetworkCredential("*****@*****.**", "123456rita*");
            MailMessage message1    = new MailMessage();
            MailAddress fromAddress = new MailAddress("*****@*****.**");

            client.Host = "smtp.gmail.com";
            client.UseDefaultCredentials = false;
            client.Credentials           = basicCredential;

            message1.From    = fromAddress;
            message1.Subject = "your subject";
            //Set IsBodyHtml to true means you can send HTML email.
            message1.IsBodyHtml = true;
            message1.Body       = "<h1>your message body</h1>";
            message1.To.Add("*****@*****.**");

            // client.Send(message1);

            MailMessage mail = new MailMessage();

            mail.From = new System.Net.Mail.MailAddress("*****@*****.**");
            SmtpClient smtp = new SmtpClient();

            smtp.Port                  = 587;
            smtp.EnableSsl             = true;
            smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials           = new NetworkCredential(mail.From.Address, "123456rita*");
            smtp.Host                  = "smtp.gmail.com";

            //recipient
            mail.To.Add(new MailAddress("*****@*****.**"));

            mail.IsBodyHtml = true;
            string st = "Test";

            mail.Body = st;
            //smtp.Send(mail);

            SmtpClient SmtpServer = new SmtpClient("smtp.live.com", 587);

            SmtpServer.Credentials           = new NetworkCredential("*****@*****.**", "123456nour");
            SmtpServer.EnableSsl             = true;
            SmtpServer.UseDefaultCredentials = false;
            //SmtpServer.Send(email);
            return(client.SendMailAsync(email));
            //using (var client = new SmtpClient()) // SmtpClient configuration comes from config file
            //{
            //    return client.SendMailAsync(email);
            //}
        }