Exemplo n.º 1
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.º 2
0
        public static bool SendEmail(string fromName, string fromAddress, string toName, string toAddress, string subject, string message)
        {
            try
            {
                var mailDefinition = new MailDefinition
                {
                    From = string.Format("{0} <{1}>", fromName, fromAddress)
                };
                var mailTo = !string.IsNullOrEmpty(toName) ? string.Format("{0} <{1}>", toName, toAddress) : toAddress;

                var mailMessage = mailDefinition.CreateMailMessage(mailTo, null, message, new Control());
                mailMessage.From       = new MailAddress(fromAddress, fromName);
                mailMessage.IsBodyHtml = true;
                mailMessage.Subject    = SubjectFormat(subject);
                var smtpClient = new SmtpClient()
                {
                    Port           = 25,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Host           = "EX-HTCA1-HO.BHF.ADS",
                };
                //send email
                smtpClient.Send(mailMessage);
                Console.WriteLine($" ... ok, sent to {mailMessage.To[0].Address} ");
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
                return(false);
            }
        }
		protected void addButton_Click(object sender, EventArgs e)
		{
			if (Page.IsValid) {
				this.addButton.Enabled = false;
				string adminMailAddressesSetting =
					ConfigurationSettings.AppSettings["AdminMailAddresses"];
				if (!string.IsNullOrEmpty(adminMailAddressesSetting)) {
					string[] adminMailAddresses = adminMailAddressesSetting.Split(new string[] { "," }, StringSplitOptions.None);

					MailDefinition md = new MailDefinition();
					md.BodyFileName = Server.MapPath(
						ConfigurationSettings.AppSettings["AddBlogMailTemplatePath"]);
					ListDictionary replacements = new ListDictionary();
					replacements.Add("<%Fullname%>", this.nameTextBox.Text);
					replacements.Add("<%BlogUrl%>", this.blogUrlTextBox.Text);
					replacements.Add("<%BlogFeedUrl%>", this.blogFeedUrlTextBox.Text);
					replacements.Add("<%EMail%>", this.emailTextBox.Text);
					MailMessage mm = null;

					mm = md.CreateMailMessage(adminMailAddressesSetting, replacements, this);
					mm.Subject = "Neue Bloganmeldung für DotNetGerman Bloggers";
					SmtpClient smtp = new SmtpClient();
					smtp.Send(mm);
					this.StateLabel.Visible = true;
				}
			}
		}
Exemplo n.º 4
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        MailDefinition md = new MailDefinition();

        md.From = "*****@*****.**";
        md.CreateMailMessage("*****@*****.**", null, this);
    }
Exemplo n.º 5
0
        //private async Task SendConfirmationEmail(string clientEmail, string code, string clientName, long clientId)
        //{
        //    var confirmURL = Url.Action("ConfirmEmail", "Account", new ConfirmEmailViewModel { EmailConfirmationCode = code, UserId = clientId }, protocol: Request.Url.Scheme);

        //    MailDefinition mailDef = new MailDefinition();
        //    mailDef.From = "*****@*****.**";
        //    mailDef.Subject = "Welcome to DogeDaycare!";
        //    mailDef.IsBodyHtml = true;

        //    ListDictionary replacements = new ListDictionary();
        //    replacements.Add("{EmailTitle}", mailDef.Subject);
        //    replacements.Add("{CustomerName}", clientName);
        //    replacements.Add("{ConfirmationLink}", confirmURL);
        //    replacements.Add("{ContactUsEmail}", mailDef.From);

        //    var body = System.IO.File.ReadAllText(Server.MapPath("~/Controllers/EmailTemplates/Inline/EmailConfirmationTemplateInline.html"));

        //    MailMessage message = mailDef.CreateMailMessage(clientEmail, replacements, body, new System.Web.UI.Control());

        //    using (var client = _smtpEmailSender.BuildClient())
        //    {
        //        await client.SendMailAsync(message);
        //    }

        //    Logger.Info(string.Format("Sent confirmation code {0} to email {1}", code, clientEmail));
        //}

        private async Task SendPasswordResetEmail(string clientEmail, string code, string clientName, long id)
        {
            var confirmURL = Url.Action("PasswordReset", "Account", new PasswordResetCodeViewModel {
                UserId = id, PasswordResetToken = code
            }, Request.Url.Scheme);

            MailDefinition mailDef = new MailDefinition();

            mailDef.From       = "*****@*****.**";
            mailDef.Subject    = "Reset your DogeDaycare password";
            mailDef.IsBodyHtml = true;

            ListDictionary replacements = new ListDictionary();

            replacements.Add("{EmailTitle}", mailDef.Subject);
            replacements.Add("{CustomerName}", clientName);
            replacements.Add("{ConfirmationLink}", confirmURL);
            replacements.Add("{ContactUsEmail}", mailDef.From);

            var body = System.IO.File.ReadAllText(Server.MapPath("~/Controllers/EmailTemplates/Inline/PasswordResetTemplateInline.html"));

            MailMessage message = mailDef.CreateMailMessage(clientEmail, replacements, body, new System.Web.UI.Control());

            using (var client = _smtpEmailSender.BuildClient())
            {
                await client.SendMailAsync(message);
            }

            Logger.Info(string.Format("Sent password reset code {0} to email {1}", code, clientEmail));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Crée le contenu d'un rapport de travail.
        /// </summary>
        /// <remarks>
        /// Crée le contenu d'un rapport de travail avec un template HTML et le replacements de valeurs spécifiques.
        /// </remarks>
        /// <param name="_workReportInformations">Liste des informations pour le rapport de travail</param>
        /// <returns>List : Réussite -> Rapport de travail. Echec -> Valeur vide.</returns>
        /// <exception cref="StreamReader, MailDefinition, MailMessage">
        /// Exception levée par l'objet StreamReader, MailDefinition ou MailMessage.
        /// </exception>
        internal static string CreateWorkReport(List <string>[] _workReportInformations)
        {
            List <string>[] workReportInformations = _workReportInformations;

            try
            {
                MailDefinition mailDefinition     = new MailDefinition();
                MailMessage    mailMessage        = new MailMessage();
                string         templateWorkReport = string.Empty;

                // Assigne des valeurs spécifiques par des paramètres.
                ListDictionary replacements = ReplacementsWorkReport(workReportInformations);

                // Lit le contenu du coprs du template HTML.
                using (StreamReader streamReader = new StreamReader(Profile_Code.Default.TemplateWorkReport))
                {
                    templateWorkReport = streamReader.ReadToEnd();
                }

                // Crée le corps du rapport de travail.
                mailDefinition.From = Profile_Val.Default.FakeEmailAdress;
                mailMessage         = mailDefinition.CreateMailMessage(Profile_Val.Default.FakeEmailAdress, replacements, templateWorkReport, new System.Web.UI.Control());

                return(mailMessage.Body);
            }
            catch
            {
                // Affiche un message d'erreur.
                MessageBox.Show(Profile_Err.Default.CreateWorkReport, Profile_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(string.Empty);
            }
        }
    private void BeniAra_MailGonder(string _SiteAdi, string _AdSoyad, string _FirmaAdi, string _IsTelefonu, string _CepTlf, string _Eposta, string _WebAdres)
    {
        string         Logo       = Ortak.SiteAdresi_http + "/Image/logo.jpg";
        MailDefinition mailTarifi = new MailDefinition();

        mailTarifi.BodyFileName = "~/EpostaSablon/EPosta_TedarikciFormu.html"; //Şablon
        mailTarifi.From         = Ortak.Eposta;
        ListDictionary degistirmeListesi = new ListDictionary();

        degistirmeListesi.Add("<%SiteAdi%>", _SiteAdi);
        degistirmeListesi.Add("<%Logo%>", Logo);
        degistirmeListesi.Add("<%AdSoyad%>", _AdSoyad);
        degistirmeListesi.Add("<%FirmaAdi%>", _FirmaAdi);
        degistirmeListesi.Add("<%IsTelefonu%>", _IsTelefonu);
        degistirmeListesi.Add("<%CepTelefonu%>", _CepTlf);
        degistirmeListesi.Add("<%EPosta%>", _Eposta);
        degistirmeListesi.Add("<%WebAdres%>", _WebAdres);
        degistirmeListesi.Add("<%Tarih%>", DateTime.Now.ToString());
        string mailTo = Ortak.EPosta_Gidicek_Adresler[0].ToString();

        MailMessage mailMesaj = mailTarifi.CreateMailMessage(mailTo, degistirmeListesi, this);

        mailMesaj.From       = new MailAddress(Ortak.Eposta, Ortak.E_Ticaret_SiteAdi);
        mailMesaj.IsBodyHtml = true;
        mailMesaj.Subject    = Ortak.SiteAdresiKısa + " | Tedarikçi Başvuru Formu";
        for (int i = 1; i < Ortak.EPosta_Gidicek_Adresler.Length; i++)
        {
            mailMesaj.Bcc.Add(new MailAddress(Ortak.EPosta_Gidicek_Adresler[i].ToString()));
        }
        //buradan sonrasını değiştirmedim, bildiğiniz gibi
        SmtpClient smtp = new SmtpClient(Ortak.MailServer, 587);

        smtp.Credentials = new NetworkCredential(Ortak.Eposta, Ortak.Sifre);
        smtp.Send(mailMesaj);
    }
        public VolarisMailer()
        {
            _mailDefinition = new MailDefinition();

            _mailDefinition.BodyFileName = Properties.Resources.VolarisMail;
            _mailDefinition.IsBodyHtml   = true;
        }
Exemplo n.º 9
0
        private static MailMessage ComposeMail(string to, string from, string subject, ListDictionary param, string bodyTemplate, FileContentResult urlAttachment)
        {
            var mailDefinition = new MailDefinition
            {
                From       = from,
                Subject    = subject,
                IsBodyHtml = true,
            };

            var mail = mailDefinition.CreateMailMessage(to, param, bodyTemplate, new System.Web.UI.Control());

            if (urlAttachment == null)
            {
                return(mail);
            }

            // Create an in-memory System.IO.Stream
            var ms = new MemoryStream(urlAttachment.FileContents);
            var ct = new ContentType(urlAttachment.ContentType);
            var a  = new Attachment(ms, ct);

            mail.Attachments.Add(a);

            return(mail);
        }
Exemplo n.º 10
0
        public bool AddMailDefinition(MailDefinitionDto obj)
        {
            try
            {
                bool isExisting = _uow.MailDefinitions.Any(x => x.EmailAddress == obj.EmailAddress);

                if (isExisting)
                {
                    return(false);
                }

                MailDefinition mailDefinition = new MailDefinition
                {
                    RecipientName = obj.RecipientName,
                    EmailAddress  = obj.EmailAddress,
                    CreatedDate   = DateTime.Now
                };

                _uow.MailDefinitions.Add(mailDefinition);
                return(_uow.Commit());
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemplo n.º 11
0
        public static Dictionary <int, MailDefinition> LoadMail(XmlDocument mailDoc)
        {
            var mailDefinitions = new Dictionary <int, MailDefinition>();

            var mailNodes = mailDoc.SelectNodes("data/Mail");

            foreach (XmlNode mailNode in mailNodes)
            {
                var index = int.Parse(mailNode?.Attributes["Index"]?.Value ?? "-1");

                if (index == -1)
                {
                    throw new InvalidOperationException("Invalid Key Item index.");
                }

                var subjectKey = mailNode?.Attributes["Subject"].Value;
                var senderKey  = mailNode?.Attributes["Sender"].Value;

                var info          = new List <string>();
                var dialogueNodes = mailNode.ChildNodes;
                var dialogueKeys  = new List <string>();
                foreach (XmlNode dialogueXml in dialogueNodes)
                {
                    dialogueKeys.Add(dialogueXml.Attributes["Key"].Value);
                }

                mailDefinitions[index] = new MailDefinition {
                    SubjectKey = subjectKey, SenderKey = senderKey, DialogueKeys = dialogueKeys
                };
            }

            return(mailDefinitions);
        }
Exemplo n.º 12
0
    public static string SendEmail(string _ToEmail, string _Subject, ListDictionary _ListDictionary, string _Body)
    {
        try
        {
            MailDefinition md = new MailDefinition();
            md.From       = AdminEmailAddress;
            md.IsBodyHtml = true;
            md.Subject    = General.ApplicationName + " : " + _Subject;

            if (!ValidEmail(_ToEmail))
            {
                _ToEmail = General.AdminEmailAddress;
            }

            MailMessage MMsg = md.CreateMailMessage(_ToEmail, _ListDictionary,
                                                    _Body, new System.Web.UI.Control());



            SmtpClient client = new SmtpClient();
            //client.EnableSsl = true;
            client.Host = "localhost";
            client.Send(MMsg);
            client.Timeout     = 100;
            client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            return("");
        }
        catch (Exception ex)
        {
            return(ex.Message);
        }
    }
    protected void Button2_Click1(object sender, EventArgs e)
    {
        string alphabets       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
        string numbers         = "1234567890";
        string characters      = "";

        characters += alphabets + small_alphabets + numbers;
        int    length = 5;
        string otp    = string.Empty;

        for (int i = 0; i < length; i++)
        {
            string character = string.Empty;
            do
            {
                int index = new Random().Next(0, characters.Length);
                character = characters.ToCharArray()[index].ToString();
            } while (otp.IndexOf(character) != -1);
            otp += character;
        }
        MailDefinition md = new MailDefinition();

        md.From       = "*****@*****.**";
        md.IsBodyHtml = true;
        //md.Subject = "Test of MailDefinition";
        ListDictionary replacements = new ListDictionary();

        replacements.Add("{name}", Label10.Text);
        replacements.Add("{otp}", otp);
        //replacements.Add("{url}", "/ICON.jpg");
        //string body = "<div style='color:red;background:yellow'>Hello {name}<br><br><br> You're from {country}.</div><br><br> <div style='color:red;background:red'>Nice To Meet You.</div>";
        string body = "<style type='text/css'>td {padding: 15px;}.auto-style1 {color: #00E600;}</style><div style='width:80%;height:80%;margin:auto;padding:20px;color:#00cc00;border:10px solid #00cc00;'><img src=\"cid:filename\"><div style='margin:50px;background-color:#f7ffe6;padding:30px'><center><h2>Thank you for using our service!</h2></center><table><tr><td>Your Email:</td><td>{name}</td></tr><tr><td>Your OTP:</td><td>{otp}</td></tr></table></div><b style='float:right;'>&copy;Copyright BooksForTechs</b></div>";

        MailMessage mm = md.CreateMailMessage(Label10.Text, replacements, body, new System.Web.UI.Control());

        //MailMessage mm = new MailMessage("*****@*****.**", "*****@*****.**");
        mm.Subject = "OTP for Online Book Store";
        SmtpClient smtp = new SmtpClient();

        smtp.Host      = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential();

        NetworkCred.UserName       = "******";
        NetworkCred.Password       = "******";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials           = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
        Label8.Text = "New OTP sent to registered email";
        SqlConnection conn = new SqlConnection(@"Data Source=HARSHIT\SQLEXPRESS;Initial Catalog=BookStore;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");

        conn.Open();
        SqlCommand cmd = new SqlCommand("update signup Set otp=@otp where email=@email", conn);

        cmd.Parameters.AddWithValue("@otp", otp);
        cmd.Parameters.AddWithValue("@email", Label10.Text);
        cmd.ExecuteNonQuery();
    }
Exemplo n.º 14
0
        public override void SendEmail(MailDefinition mail, bool throwException)
        {
            var channel    = _channelService.Get(mail.ChannelSystemId);
            var mailSender = _websiteService.Get(channel.WebsiteSystemId.Value)?.Fields.GetValue <string>(AcceleratorWebsiteFieldNameConstants.SenderEmailAddress);

            switch (mail)
            {
            case PlainMailDefinition plainTextMail:
                SendEmail(mailSender, plainTextMail.ToEmail, plainTextMail.Subject, plainTextMail.Body, false, throwException);
                return;

            case HtmlMailDefinition htmlTextMail:
                SendEmail(mailSender, htmlTextMail.ToEmail, htmlTextMail.Subject, htmlTextMail.Body, true, throwException);
                return;
            }

            if (!(mail is PageMailDefinition pageMail))
            {
                return;
            }

            var page    = pageMail.Page;
            var pageUrl = _urlService.GetUrl(page, new PageUrlArgs(pageMail.ChannelSystemId)
            {
                AbsoluteUrl = true
            });
            var url = pageMail.UrlTransform(pageUrl);

            var baseUrl = _urlService.GetUrl(channel, new ChannelUrlArgs {
                AbsoluteUrl = true
            });

            if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var baseUri))
            {
                return;
            }

            if (string.IsNullOrEmpty(mailSender))
            {
                _logger.LogError("Sending e-mail failed. Mail sender was empty. Check mail configuration settings");
                if (throwException)
                {
                    throw new Exception("Mail sender was empty. Check mail configuration settings");
                }

                return;
            }

            var messageInfo = new MessageInfo
            {
                FromEmail    = mailSender,
                ToEmail      = pageMail.ToEmail,
                Subject      = pageMail.Subject,
                Url          = url,
                PageSystemId = page.SystemId,
                BaseUrl      = baseUrl
            };

            _schedulerService.ScheduleJob <MailServiceProcessor>(x => x.Process(messageInfo));
        }
    private void Kargo_MailGonder(string _SiteAdi, string _AdSoyad, string _SiparisNo, string _TakipNo, string _KargoFirmasi, string _link, string _Eposta_Musteri)
    {
        string         Logo       = Ortak.SiteAdresi_http + "/Image/logo.jpg";
        MailDefinition mailTarifi = new MailDefinition();

        mailTarifi.BodyFileName = "~/EpostaSablon/EPosta_KargoTeslimati.html"; //Şablon
        mailTarifi.From         = Ortak.Eposta;
        ListDictionary degistirmeListesi = new ListDictionary();

        degistirmeListesi.Add("<%SiteAdi%>", _SiteAdi);
        degistirmeListesi.Add("<%Logo%>", Logo);
        degistirmeListesi.Add("<%AdSoyad%>", _AdSoyad);
        degistirmeListesi.Add("<%SiparisNo%>", _SiparisNo);
        degistirmeListesi.Add("<%KargoTakipNo%>", _TakipNo);
        degistirmeListesi.Add("<%KargoFirmasi%>", _KargoFirmasi);
        degistirmeListesi.Add("<%KargoTakipLinki%>", _link);
        string      mailTo    = Ortak.EPosta_Gidicek_Adresler[0].ToString();
        MailMessage mailMesaj = mailTarifi.CreateMailMessage(mailTo, degistirmeListesi, this);

        mailMesaj.From       = new MailAddress(Ortak.Eposta, Ortak.E_Ticaret_SiteAdi);
        mailMesaj.IsBodyHtml = true;
        mailMesaj.Subject    = Ortak.SiteAdresiKısa + " | Kargo Gönderim Bildirimi";
        for (int i = 1; i < Ortak.EPosta_Gidicek_Adresler.Length; i++)
        {
            mailMesaj.Bcc.Add(new MailAddress(Ortak.EPosta_Gidicek_Adresler[i].ToString()));
        }
        mailMesaj.Bcc.Add(new MailAddress(_Eposta_Musteri));
        //buradan sonrasını değiştirmedim, bildiğiniz gibi
        SmtpClient smtp = new SmtpClient(Ortak.MailServer, 587);

        smtp.Credentials = new NetworkCredential(Ortak.Eposta, Ortak.Sifre);
        smtp.Send(mailMesaj);
    }
Exemplo n.º 16
0
        /**
         * CLIENT -  PAYMENT SUCCESSFUL
         * Send email to client on payment success
         */
        public string SendMailClientPayment(int jobId, string renterMail, string mailType, string renterName, string site)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("mail.realwheelsdavao.com"); //smtp server

                MailDefinition md = new MailDefinition();
                md.From       = "*****@*****.**"; //sender mail
                md.IsBodyHtml = true;                                         //set true to enable use of html tags
                md.Subject    = "RealWheels Reservation";                     //mail title

                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%To%>", renterMail);
                replacements.Add("<%From%>", md.From);

                string body, message;
                string siteName = site;
                //get job details

                //send email in /joborder
                JobMain job = db.JobMains.Find(jobId);
                //mail title
                md.Subject = "Payment Success";

                //encode white space
                string jobDesc = System.Web.HttpUtility.UrlPathEncode(job.Description);

                //mail content for client inquiries

                message = "Thank you for your payment. Please follow the link for the invoice and payment. <a href='" + siteName + "" + jobId + "/" + job.JobDate.Month + "/" + job.JobDate.Day + "/" + job.JobDate.Year + "/" + jobDesc + "/' " +
                          "> View Invoice </a> ";
                //" style='display:block;background-color:dodgerblue;margin:20px;padding:20px;text-decoration:none;font-weight:bolder;font-size:300;color:white;border-radius:3px;min-width:100px;'> View Invoice </a> ";

                body =
                    "" +
                    // " <p>Hello {name}, You have booked a {tour} and  {unit} {type} for {days} day(s). The total cost of the package is {total}. </p>" +
                    " <div style='background-color:#f4f4f4;padding:20px' align='center'>" +
                    " <div style='background-color:white;min-width:200px;margin:30px;padding:30px;text-align:center;color:#555555;font:normal 300 16px/21px 'Helvetica Neue',Arial'>  <h1> Payment Successful </h1>" +
                    message +
                    " <p> This is an auto-generated email. DO NOT REPLY TO THIS MESSAGE. </p> " +
                    " <p> For further inquiries kindly email us through [email protected] or dial(+63) 82 297 1831. </p> " +
                    " </div></div>" +
                    "";

                MailMessage msg = md.CreateMailMessage(renterMail, replacements, body, new System.Web.UI.Control());

                SmtpServer.Port        = 587;   //default smtp port
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Real123!");
                SmtpServer.EnableSsl   = false; //enable for gmail smtp server
                System.Net.ServicePointManager.Expect100Continue = false;
                SmtpServer.Send(msg);           //send message
                return("success");
            }
            catch (Exception ex)
            {
                return("error: " + ex);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            SetPasswordRecoverControlProperties();
            MailSettings   mailSettings   = MessagingCache.GetMailSettings();
            MailDefinition mailDefinition = prPasswordRecover.MailDefinition;

            mailDefinition.From = mailSettings.From;
        }
Exemplo n.º 18
0
    private void SendSubmitMail()
    {
        MailDefinition def = new MailDefinition();

        def.IsBodyHtml   = true;
        def.BodyFileName = "~/mail-templates/submit-club.html";
        def.Subject      = "RC Map - Club Submitted";
        MailUtility.Send(def.CreateMailMessage(Configuration.EmailsTo, GetTemplateReplacements(), this));
    }
Exemplo n.º 19
0
        //Send Email to the [renterMail] one at a time,
        //[emailSubject] as email title,
        //[emailContent] as email body,
        //[emalPicture] as Picture Link to <img>,
        //[emailAttachmentLink] as Attachment link to <a>
        public string SendMailBlaster(string renterMail, string emailSubject, string emailContent, string emailPicture, string emailAttachmentLink, string company)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("mail.realwheelsdavao.com"); //smtp server

                MailDefinition md = new MailDefinition();
                md.From       = "*****@*****.**"; //sender mail
                md.IsBodyHtml = true;                                         //set true to enable use of html tags
                md.Subject    = emailSubject;                                 //mail title

                ListDictionary replacements = new ListDictionary();
                replacements.Add("{name}", "Martin");

                string body, message;

                //mail content for client inquiries
                message = emailContent;

                //build email body
                body =
                    "" +
                    " <div style='background-color:#f4f4f4;padding:20px' align='center'>" +
                    " <div style='background-color:white;min-width:250px;margin:20px;padding:0px;text-align:center;color:#555555;font:normal 300 16px/21px 'Helvetica Neue',Arial;'> " +
                    handleCompany(company) +
                    " <h1 style='text-align:center;padding-bottom:20px;margin-top:-60px;'> " + emailSubject + " </h1>" +
                    handlePictureLink(emailPicture) +
                    " <div style='text-align:left;padding:20px;'><h3>" +
                    message +
                    " </h3></div>" +
                    handleAttachLink(emailAttachmentLink) +
                    " <br />" +
                    " </div>" +
                    " <div style='text-align:center;color:#626262;'>" +
                    " <p> This is an auto-generated email. DO NOT REPLY TO THIS MESSAGE </p> " +
                    " <p> For inquiries, kindly email us through [email protected] or dial(+63) 82 297 1831. </p> " +
                    " </div>" +
                    " </div>" +
                    "       ";

                MailMessage msg = md.CreateMailMessage(renterMail, replacements, body, new System.Web.UI.Control());
                //msg.Attachments.Add(new Attachment(emailPicture));

                SmtpServer.Port        = 587;   //default smtp port
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Real123!");
                SmtpServer.EnableSsl   = false; //enable for gmail smtp server
                System.Net.ServicePointManager.Expect100Continue = false;
                SmtpServer.Send(msg);           //send message
                return("success");
            }
            catch (Exception ex)
            {
                return("error: " + ex);
            }
        }
Exemplo n.º 20
0
        private string GetEmailTemplate()
        {
            MailDefinition mailDef    = new MailDefinition();
            string         currentDir = Environment.CurrentDirectory;

            EmailTemplate = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                         Path.Combine("bin", "EmailHelper", EmailTemplate + ".html"));
            mailDef.BodyFileName = EmailTemplate;
            return(mailDef.CreateMailMessage(_fromAddress.Address, _emailData, new System.Web.UI.Control()).Body);
        }
Exemplo n.º 21
0
 public DisciturMailDef(ListDictionary replacements)
 {
     config        = MailConfigProvider.GetConfiguration <T>();
     MailTemplate  = config.Template;
     Replacements  = replacements;
     md            = new MailDefinition();
     md.IsBodyHtml = true;
     md.Subject    = config.Subject;
     md.From       = config.From;
 }
Exemplo n.º 22
0
        public MailItemViewModel(int index, MailDefinition mailDefinition)
        {
            this.index        = index;
            this.senderKey    = mailDefinition.SenderKey;
            this.subjectKey   = mailDefinition.SubjectKey;
            this.DialogueKeys = new ObservableCollection <Wrapper <string> >(mailDefinition.DialogueKeys.Select(k => k.Wrap()) ?? new List <Wrapper <string> >());
            this.DialogueKeys.CollectionChanged += CollectionChanged;
            this.RegisterDialogueKeys();

            this.initialStringValue = this.StringValue;
        }
Exemplo n.º 23
0
        private bool SendReport(List <MessageReceiver> receivers, string messageSubject, string messageBody)
        {
            try
            {
                SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                try
                {
                    MailDefinition mailDefinition = new MailDefinition();
                    mailDefinition.From       = new MailAddress(smtpSection.From).ToString();
                    mailDefinition.Subject    = !string.IsNullOrEmpty(messageSubject) ? string.Format("{0} {1} {2}", _4screen.CSB.Common.SiteConfig.SiteName, language.GetString("TextMessageFeedback"), messageSubject) : string.Format("{0} {1}", _4screen.CSB.Common.SiteConfig.SiteName, language.GetString("TextMessageFeedback"));
                    mailDefinition.IsBodyHtml = true;

                    ListDictionary replacements = new ListDictionary();
                    replacements.Add("<%SITE_URL%>", _4screen.CSB.Common.SiteConfig.SiteURL);
                    if (UserDataContext.GetUserDataContext().IsAuthenticated)
                    {
                        replacements.Add("<%FROM_USERNAME%>", UserDataContext.GetUserDataContext().Nickname);
                    }
                    else
                    {
                        replacements.Add("<%FROM_USERNAME%>", UserDataContext.GetUserDataContext().AnonymousUserId.ToString());
                    }

                    string preparedLink = rawLink;
                    if (!rawLink.ToLower().StartsWith("http"))
                    {
                        preparedLink = _4screen.CSB.Common.SiteConfig.HostName + rawLink;
                    }

                    replacements.Add("<%LINK%>", preparedLink);
                    GuiLanguage languageReport = GuiLanguage.GetGuiLanguage(CustomizationSection.CachedInstance.ContentReports.LocalizationBaseFileName);
                    replacements.Add("<%REASON%>", languageReport.GetString(rcbReport.SelectedValue));
                    replacements.Add("<%USER_MESSAGE%>", messageBody);

                    string      mailBody    = GuiLanguage.GetGuiLanguage("Templates").GetString("EmailObjectReport");
                    MailMessage mailMessage = mailDefinition.CreateMailMessage(string.Join(",", receivers.FindAll(x => !string.IsNullOrEmpty(x.EmailAddress)).Select(x => x.EmailAddress).ToArray()), replacements, mailBody, this);

                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Send(mailMessage);

                    return(true);
                }
                catch (Exception exception)
                {
                    LogManager.WriteEntry(exception);
                    return(false);
                }
            }
            catch (Exception exception)
            {
                LogManager.WriteEntry(exception);
                return(false);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Crée le contenu d'un message.
        /// </summary>
        /// <remarks>
        /// Crée le contenu d'un message avec un template HTML.
        /// </remarks>
        /// <param name="_pathFile">Chemin du fichier</param>
        /// <param name="_emailInformations">Informations de l'email</param>
        /// <returns>String : Réussite -> Corps, destinataire et sujet du message. Echec -> Valeur null.</returns>
        /// <exception cref="StreamReader, MailDefinition, MailMessage">
        /// Exception levée par l'objet StreamReader, MailDefinition ou MailMessage.
        /// </exception>
        private static List <string> CreateBodyMessage(string _filePath, List <string> _emailInformations)
        {
            string        filePath          = _filePath;
            List <string> emailInformations = _emailInformations;

            // Vérifie le contenu de la liste.
            if (IsNullList(emailInformations))
            {
                // Affiche un message d'erreur.
                MessageBox.Show(SentOffer_Val.Default.NullEmailAdress, SentOffer_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }

            try
            {
                string         templateConfirm         = string.Empty;
                List <string>  bodyMessageInformations = new List <string>();
                MailDefinition mailDefinition          = new MailDefinition();
                MailMessage    mailMessage             = new MailMessage();

                // Assigne des valeurs spécifiques par des paramètres.
                ListDictionary replacements = ReplacementsMessage(emailInformations);

                // Lit le contenu du coprs du template HTML.
                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    templateConfirm = streamReader.ReadToEnd();
                }

                // Assigne le sujet du message.
                int    indexSubject  = (templateConfirm.IndexOf(SentOffer_Code.Default.OpenTitleBalise) + SentOffer_Code.Default.OpenTitleBalise.Length);
                int    lengthSubject = (templateConfirm.LastIndexOf(SentOffer_Code.Default.CloseTitleBalise) - indexSubject);
                string subject       = templateConfirm.Substring(indexSubject, lengthSubject);

                // Crée le corps du message modifié.
                mailDefinition.From = SentOffer_Val.Default.FakeEmailAdress;
                mailMessage         = mailDefinition.CreateMailMessage(emailInformations[1], replacements, templateConfirm, new System.Web.UI.Control());

                // Assigne le destinataire, le corps et le sujet du message.
                bodyMessageInformations.Add(mailMessage.To.ToString());
                bodyMessageInformations.Add(mailMessage.Body);
                bodyMessageInformations.Add(subject);

                return(bodyMessageInformations);
            }
            catch
            {
                // Affiche un message d'erreur.
                MessageBox.Show(SentOffer_Err.Default.CreateBodyMessage, SentOffer_Err.Default.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
Exemplo n.º 25
0
        public static void SendMailHtml(List <string> to, string subject, string htmlBodyFilePath, Hashtable replacements, List <string> cc, List <MailAddress> bcc, List <System.Net.Mail.Attachment> attachments)
        {
            try
            {
                var        SmtpConfig = ConfigurationManager.GetSection("SMTP") as SMTP;
                SmtpClient SmtpServer = new SmtpClient(SmtpConfig.SMTPServerName);
                SmtpServer.Port        = SmtpConfig.Port;
                SmtpServer.Credentials = new System.Net.NetworkCredential(SmtpConfig.Username, SmtpConfig.Password);
                SmtpServer.EnableSsl   = SmtpConfig.SSLEncripted;

                MailDefinition md = new MailDefinition();
                md.From    = SmtpConfig.DefaultFromEmail;
                md.Subject = subject;
                string toRecipiants = string.Join(";", to);
                md.IsBodyHtml = true;
                string sbody = string.Empty;

                //get file path in project
                string     codeBase = Assembly.GetExecutingAssembly().CodeBase;
                UriBuilder uri      = new UriBuilder(codeBase);
                string     path     = Uri.UnescapeDataString(uri.Path);
                string     dir      = Path.GetDirectoryName(path);

                StreamReader reader = new StreamReader(dir + htmlBodyFilePath);
                sbody = reader.ReadToEnd();

                MailMessage mail = md.CreateMailMessage(toRecipiants, replacements, sbody, new System.Web.UI.Control());
                if (bcc != null)
                {
                    foreach (var item in bcc)
                    {
                        mail.Bcc.Add(item.Address);
                    }
                }

                if (attachments != null)
                {
                    foreach (var item in attachments)
                    {
                        mail.Attachments.Add(item);
                    }
                }
                SmtpServer.Send(mail);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        MailDefinition md = new MailDefinition();
        md.BodyFileName = "mailtemplate.txt";

        Dictionary<string, string> d = new Dictionary<string, string>();
        d.Add("<customer>", "ACME Global");
        d.Add("<amount>", ".0002 cents");

        MailMessage m = md.CreateMailMessage("*****@*****.**", d, new LiteralControl());
        m.Subject = "account review";
        m.From = new MailAddress("*****@*****.**");

        SmtpClient smtp = new SmtpClient();
        smtp.Send(m);
    }
Exemplo n.º 27
0
        public void NewPostEmail(IEnumerable <Subscription> Subs, Post ThePost, Thread thread, string PostURL)
        {
            ListDictionary replacements  = new ListDictionary();
            string         AutoFromEmail = SiteConfig.AutomatedFromEmail.Value;

            MailDefinition md = new MailDefinition();

            md.BodyFileName = EmailTemplates.GenerateEmailPath(EmailTemplates.NewThreadReply);
            md.IsBodyHtml   = true;
            md.From         = AutoFromEmail;
            md.Subject      = "Reply to Thread '" + thread.Title + "' - " + SiteConfig.BoardName.Value;

            replacements.Add("{REPLY_USERNAME}", ThePost.User.Username);
            replacements.Add("{REPLY_TEXT}", ThePost.Text);
            replacements.Add("{THREAD_TITLE}", thread.Title);
            replacements.Add("{POST_URL}", PostURL);
            replacements.Add("{BOARD_URL}", SiteConfig.BoardURL.Value);
            replacements.Add("{BOARD_NAME}", SiteConfig.BoardName.Value);

            System.Web.UI.Control ctrl = new System.Web.UI.Control {
                ID = "Something"
            };

            MailMessage message = md.CreateMailMessage("*****@*****.**", replacements, ctrl);

            //Send the message
            SmtpClient client = Settings.GetSmtpClient();

            foreach (Subscription s in Subs)
            {
                if (s.UserID == ThePost.UserID)
                {
                    continue;
                }
                User u = s.User;
                message.To.Clear();
                message.To.Add(u.Email);
                try
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(state => client.Send(message));
                }
                catch
                {
                }
            }
        }
Exemplo n.º 28
0
        public static void SendEmail(TB_APPLICATION_SCHOOL school, String registerdPassword, String culture)
        {
            try
            {
                String templateName = (culture.ToUpper().Equals("TH")) ? "AccountDetail_th.html" : "AccountDetail_en.html";
                String emailSubject = (culture.ToUpper().Equals("TH")) ? "การลงทะเบียนเข้าร่วมการแข่งขัน" : "การลงทะเบียนเข้าร่วมการแข่งขัน";
                String displanName  = (culture.ToUpper().Equals("TH")) ? "การแข่งขันภาษาจีนเพชรยอดมงกุฎ ครั้งที่ 12 (นานาชาติ)" : "การแข่งขันภาษาจีนเพชรยอดมงกุฎ ครั้งที่ 12  (นานาชาติ)";

                MailDefinition mailDefinition = new MailDefinition();
                mailDefinition.BodyFileName = "~/Utils/Email-Templates/" + templateName;
                mailDefinition.From         = EmailUser;



                //Create a key-value collection of all the tokens you want to replace in your template...
                ListDictionary ldReplacements = new ListDictionary();
                ldReplacements.Add("<%School Name%>", school.SCHOOL_NAME);
                ldReplacements.Add("<%User%>", school.SCHOOL_EMAIL.Trim());
                ldReplacements.Add("<%Password%>", registerdPassword.Trim());

                string      mailTo      = string.Format("{0} <{1}>", school.SCHOOL_NAME, school.SCHOOL_EMAIL);
                MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, ldReplacements, new System.Web.UI.Control());
                mailMessage.From            = new MailAddress(EmailUser, displanName);
                mailMessage.IsBodyHtml      = true;
                mailMessage.Subject         = emailSubject;
                mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

                // smtp settings
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
                {
                    smtpClient.Host           = Host;
                    smtpClient.Port           = Port;
                    smtpClient.EnableSsl      = true;
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Credentials    = new NetworkCredential(EmailUser, EmailPassword);
                    smtpClient.Timeout        = 20000;
                }
                //SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString(), 25);
                smtpClient.Send(mailMessage);
            }
            catch (Exception ex)
            {
                //throw ex;
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Return true if message send succsesfully, false if message send with errors
        /// </summary>
        /// <param name="emailModel"></param>
        /// <returns></returns>
        public static bool SendEmail(Email emailModel)
        {
            string smtpStr  = ConfigurationData.GetEmailServer();
            int    portInt  = ConfigurationData.GetEmailPort();
            string userStr  = ConfigurationData.GetEmailUser();
            string passStr  = ConfigurationData.GetEmailPass();
            string emailStr = ConfigurationData.GetAdminEmail();
            bool   sslBool  = ConfigurationData.GetEmailSsl();

            MailDefinition mailDefinition = new MailDefinition();

            mailDefinition.BodyFileName = "~/Content/tmp/TemplateEmail.html";
            mailDefinition.From         = userStr;
            ListDictionary replacements = new ListDictionary();

            replacements.Add("<%Title%>", emailModel.Title);
            replacements.Add("<%Name%>", emailModel.Name);
            replacements.Add("<%PhoneNumber%>", emailModel.PhoneNumber);
            replacements.Add("<%Message%>", emailModel.Message);
            replacements.Add("<%BestTime%>", emailModel.ContactTime);

            string      mailTo      = string.Format("{0} <{1}>", "Administrator", emailStr);
            MailMessage mailMessage = mailDefinition.CreateMailMessage(mailTo, replacements, new System.Web.UI.Control());

            mailMessage.IsBodyHtml = true;
            mailMessage.Subject    = "Feedback";

            SmtpClient smtp = new SmtpClient();

            smtp.Host = smtpStr;
            smtp.Port = portInt;

            smtp.Credentials = new NetworkCredential(userStr, passStr);
            smtp.EnableSsl   = sslBool;
            try
            {
                smtp.Send(mailMessage);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public static bool SendContactFormMail(USNContactFormViewModel model, string mailTo, string websiteName, string pageName, out string lsErrorMessage)
        {
            lsErrorMessage = String.Empty;

            try
            {
                //Create MailDefinition
                MailDefinition md       = new MailDefinition();
                string         lsSendTo = String.Empty;

                //specify the location of template
                md.BodyFileName = "/usn/emailtemplates/contactform.htm";
                md.IsBodyHtml   = true;

                //Build replacement collection to replace fields in template
                System.Collections.Specialized.ListDictionary replacements = new System.Collections.Specialized.ListDictionary();
                replacements.Add("<% formFirstName %>", model.FirstName == null ? "" : model.FirstName);
                replacements.Add("<% formLastName %>", model.LastName == null ? "" : model.LastName);
                replacements.Add("<% formEmail %>", model.Email == null ? "" : model.Email);
                replacements.Add("<% formPhone %>", model.Telephone == null ? "" : model.Telephone);
                replacements.Add("<% formMessage %>", model.Message == null ? "" : umbraco.library.ReplaceLineBreaks(model.Message));
                replacements.Add("<% WebsitePage %>", pageName);
                replacements.Add("<% WebsiteName %>", websiteName);

                lsSendTo = mailTo;

                //now create mail message using the mail definition object
                System.Net.Mail.MailMessage msg = md.CreateMailMessage(lsSendTo, replacements, new System.Web.UI.Control());
                msg.ReplyToList.Add(model.Email);
                msg.Subject = websiteName + " Website: " + pageName + " Page Enquiry";

                //this uses SmtpClient in 2.0 to send email, this can be configured in web.config file.
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Send(msg);

                return(true);
            }
            catch (Exception ex)
            {
                lsErrorMessage = ex.Message;
            }

            return(false);
        }
Exemplo n.º 31
0
        public static void SendMail(string templateName, string sendTo, string cc, string subject, Dictionary <string, string> replacements, MailPriority priority = MailPriority.Normal, bool writeAsFile = false)
        {
            MailDefinition md = new MailDefinition();

            md.BodyFileName = templateName;
            md.CC           = cc;
            md.From         = @"*****@*****.**";
            md.Subject      = subject;
            md.IsBodyHtml   = true;
            MailMessage msg = md.CreateMailMessage(@sendTo, null, new System.Web.UI.Control());

            foreach (var r in replacements)
            {
                string placeholder = String.Format(@"<%{0}%>", r.Key);
                msg.Body = msg.Body.Replace(placeholder, r.Value);
            }
            //string recipient, string subject,string body
            IncidentsController.SendEmail(sendTo, subject, msg.Body);
        }
Exemplo n.º 32
0
        private static void CreateEmail(string CustomerEmail, string emailBody, MailDefinition md, ListDictionary replacements, string p)
        {
            MailMessage msg = md.CreateMailMessage(CustomerEmail, replacements, emailBody, new System.Web.UI.Control());

            //Define SMTP Connection
            SmtpClient client = new SmtpClient()
            {
                Port           = 587,
                EnableSsl      = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                //UseDefaultCredentials = true,
                Credentials = new System.Net.NetworkCredential("*****@*****.**", p),
                Host        = "smtp.office365.com"
            };

            // Send email
            client.Send(msg);
            msg.Dispose();
        }
    private int sendPwdRstMail(string destinationAddress, string user, string password)
    {
        int flag = 5;// E-mail successfully sent
            try
            {
                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%UserName%>", user);
                replacements.Add("<%Password%>", password);

                MailDefinition mailDef = new MailDefinition();
                mailDef.IsBodyHtml = true;

                //location of the mail template
                mailDef.BodyFileName = "~/Utilities/EmailTemplates/resetAccountPasswordByAdmin.html";
                mailDef.Subject = "Account Password Reset By Administrator";
                mailDef.From = "*****@*****.**";
                mailDef.Priority = MailPriority.High;

                //-------------------------------
                MailMessage mail = mailDef.CreateMailMessage(destinationAddress, replacements,this);
                //from address
                mail.From = new System.Net.Mail.MailAddress("*****@*****.**"); //Dummy Address
                SmtpClient smtp = new SmtpClient();

                smtp.Send(mail);
                //-------------------------------
            }
            catch (Exception)
            {
                flag = 4; //Unable to send E-mail - contact administrator
                return flag;
            }
            finally
                {
                }
            return flag;
    }