Example #1
0
        static void Main()
        {
            IMail email = Mail
                .Html(@"<img src=""cid:lemon@id"" align=""left"" /> This is simple 
                        <strong>HTML email</strong> with an image and attachment")
                .Subject("Subject")
                .AddVisual("Lemon.jpg").SetContentId("lemon@id")
                .AddAttachment("Attachment.txt").SetFileName("Invoice.txt")
                .From(new MailBox("*****@*****.**", "Lemon Ltd"))
                .To(new MailBox("*****@*****.**", "John Smith"))
                .Create();

            email.Save(@"SampleEmail.eml");     // You can save the email for preview.

            using (Smtp smtp = new Smtp())      // Now connect to SMTP server and send it
            {
                smtp.Connect(_server);          // Use overloads or ConnectSSL if you need to specify different port or SSL.
                smtp.Ehlo();
                smtp.Login(_user, _password);   // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                // or use UseBestLogin method if you want Mail.dll to choose for you.
                smtp.SendMessage(email);

                smtp.Close();
            }

            // For sure you'll need to send more advanced emails, 
            // take a look at our templates support in SmtpTemplates sample.
        }
Example #2
0
        private void SendMessageClick(object sender, RoutedEventArgs e)
        {
            MailBuilder builder = new MailBuilder();

            builder.From.Add(new MailBox(from_textBox.Text, "Hello"));
            builder.To.Add(new MailBox(to_textBox.Text, "World"));
            builder.Subject = subject_textBox.Text;
            builder.Text    = messageText_textBox.Text;

            IMail email = builder.Create();

            // отправка сообщения
            using (Smtp smtp = new Smtp())
            {
                smtp.ConnectSSL("smtp.gmail.com");
                smtp.UseBestLogin("email", "password"); //вставляем email и пароль

                ISendMessageResult result = smtp.SendMessage(email);
                if (result.Status == SendMessageStatus.Success)
                {
                    MessageBox.Show("Сообщение отправленно!");
                }
                smtp.Close();
            }
        }
Example #3
0
        static void Main()
        {
            IMail email = Mail
                          .Html(@"<img src=""cid:lemon@id"" align=""left"" /> This is simple 
                        <strong>HTML email</strong> with an image and attachment")
                          .Subject("Subject")
                          .AddVisual("Lemon.jpg").SetContentId("lemon@id")
                          .AddAttachment("Attachment.txt").SetFileName("Invoice.txt")
                          .From(new MailBox("*****@*****.**", "Lemon Ltd"))
                          .To(new MailBox("*****@*****.**", "John Smith"))
                          .Create();

            email.Save(@"SampleEmail.eml");             // You can save the email for preview.

            using (Smtp smtp = new Smtp())              // Now connect to SMTP server and send it
            {
                smtp.Connect(_server);                  // Use overloads or ConnectSSL if you need to specify different port or SSL.
                smtp.UseBestLogin(_user, _password);    // You can also use: Login, LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                        // or use UseBestLogin method if you want Mail.dll to choose for you.

                ISendMessageResult result = smtp.SendMessage(email);
                Console.WriteLine(result.Status);

                smtp.Close();
            }

            // For sure you'll need to send complex emails,
            // take a look at our templates support in SmtpTemplates sample.
        }
Example #4
0
        static void send(string subject, User to)
        {
            try
            {
                MailBuilder builder = new MailBuilder();
                builder.Html    = @"Html with an image: <img src=""cid:lena"" />";
                builder.Subject = subject;


                MimeData visual = builder.AddVisual(HostingEnvironment.MapPath("~/Images/logo_2.png"));
                visual.ContentId = "lena";

                MimeData attachment = builder.AddAttachment(@"C:\Users\User\Desktop\Attachment.txt");
                attachment.FileName = "document.doc";

                builder.From.Add(new MailBox("*****@*****.**"));
                builder.To.Add(new MailBox(to.Email));
                //builder.To.Add(new MailBox("*****@*****.**"));
                IMail email = builder.Create();

                using (Smtp smtp = new Smtp())
                {
                    smtp.Connect(_server);       // or ConnectSSL for SSL
                    smtp.UseBestLogin(_user, _password);

                    smtp.SendMessage(email);

                    smtp.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #5
0
        private void SendAowEmail(IMail theGameEmail)
        {
            try
            {
                using (Smtp smtp = new Smtp())
                {
                    switch (_sslType)
                    {
                    case SSLType.None:
                        smtp.Connect(_host, _port);
                        break;

                    case SSLType.SSL:
                        smtp.ConnectSSL(_host, _port);
                        break;

                    case SSLType.TLS:
                        smtp.Connect(_host, _port);
                        smtp.StartTLS();
                        break;
                    }

                    if (!string.IsNullOrEmpty(_username) &&
                        !string.IsNullOrEmpty(_password))
                    {
                        smtp.UseBestLogin(_username, _password);
                    }

                    if (_bccMyself)
                    {
                        theGameEmail.Bcc.Add(theGameEmail.From[0]);
                    }

                    smtp.SendMessage(theGameEmail);

                    smtp.Close();
                }
                Trace.WriteLine(string.Format("EMAIL: [{0}] Message sent successfully.", theGameEmail.To[0].GetMailboxes()[0].Address));
                RaiseOnEmailSentEvent(new SmtpSendResponse(theGameEmail, true));
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("EMAIL: [{0}] {1}", theGameEmail.To, ex.ToString()));

                if (IsRetrySend(theGameEmail.MessageID))
                {
                    //Try again
                    _messageIDsBeingSent.Remove(theGameEmail.MessageID);
                    Trace.WriteLine(string.Format("EMAIL: [{0}] Retry: {1}", theGameEmail.To, _messageSendAttemptCount[theGameEmail.MessageID]));
                }
                else
                {
                    //Send FAILED
                    RaiseOnEmailSentEvent(new SmtpSendResponse(theGameEmail, false, ex));
                }
            }
            ProcessMessageQueue();
        }
Example #6
0
        public IActionResult BlogNotificationMailSend(int id)
        {
            try
            {
                var    setting     = settingRepository.GetById(1);
                var    emailList   = emailRegRepository.GetAll().Select(p => p.EmailAddress).ToList();
                var    blog        = blogRepository.GetById(id);
                string messageHtml = "" +
                                     "<div style='background-color:#F7F7F7;padding:5px;'>" +
                                     "<div style='background-color:#FFF;padding:5px;'>" +
                                     "<h3 style='text-align:center'>" + blog.Title + "</h3>" +
                                     "<p style='text-align:center'><img src='https://" + setting.SiteName + "/img/" + blog.ImageUrl + "' width='400px'/></p>" +
                                     "<p style='text-align:justify'>" + blog.Explanation + "...</p>" +
                                     "<a href='https://" + setting.SiteName + "/Home/Detail/" + blog.BlogId + "' style='text-decoration:none;text-align:center;display:block; background-color:#007bff;color:#fff;padding:10px 15px;border-radius:15px'>Makeleye Git</a>" +
                                     "<hr/>" +
                                     "<p>E-Posta aboneliğimizden çıkmak için <a href='https://" + setting.SiteName + "/Home/EmailCancellation'>buraya tıklayarak</a> ilgili adrese gidiniz.</p>" +
                                     "</div>" +
                                     "</div>";

                MailBuilder builder = new MailBuilder();

                builder.From.Add(new MailBox(setting.SMTPServerFrom, setting.SMTPServerFromName));
                builder.To.Add(new MailGroup("Undisclosed recipients"));

                foreach (string item in emailList)
                {
                    builder.Bcc.Add(new MailBox(item));
                }

                builder.Subject = blog.Title;
                builder.Html    = messageHtml;

                IMail email = builder.Create();

                using Smtp smtp = new Smtp();
                smtp.Connect(setting.SMTPServerHost, Convert.ToInt32(setting.SMTPServerPort)); // or ConnectSSL for SSL
                smtp.UseBestLogin(setting.SMTPServerUsername, setting.SMTPServerPassword);     // remove if not needed
                smtp.SendMessage(email);
                smtp.Close();

                blog.IsMailSend = true;
                if (blogRepository.UpdateBlog(blog))
                {
                    TempData["MailNotificationSuccess"] = "'" + blog.Title + "', bloğu için e-posta bildirimleri gönderildi.";
                }
            }
            catch
            {
                TempData["MailNotificationDanger"] = "E-Posta bildirimi gönderilirken bir hata oluştu!";
            }

            return(RedirectToAction("List"));
        }
Example #7
0
        static void Main()
        {
            // Create test data for the template:
            Order order = new Order();

            order.OrderId      = 7;
            order.CustomerName = "John Smith";
            order.Currency     = "USD";
            order.Items.Add(new OrderItem {
                Name = "Yellow Lemons", Quantity = "22 lbs", Price = 149
            });
            order.Items.Add(new OrderItem {
                Name = "Green Lemons", Quantity = "23 lbs", Price = 159
            });

            // Load and render the template with test data:
            string html = Template
                          .FromFile("Order.template")
                          .DataFrom(order)
                          .PermanentDataFrom(DateTime.Now) // Year is used in the email footer/
                          .Render();

            // You can save the HTML for preview:
            File.WriteAllText("Order.html", html);

            // Create an email:
            IMail email = Mail.Html(Template
                                    .FromFile("Order.template")
                                    .DataFrom(order)
                                    .PermanentDataFrom(DateTime.Now)
                                    .Render())
                          .Text("This is text version of the message.")
                          .AddVisual("Lemon.jpg").SetContentId("lemon@id") // Here we attach an image and assign the content-id.
                          .AddAttachment("Attachment.txt").SetFileName("Invoice.txt")
                          .From(new MailBox("*****@*****.**", "Lemon Ltd"))
                          .To(new MailBox("*****@*****.**", "John Smith"))
                          .Subject("Your order")
                          .Create();

            // Send this email:
            using (Smtp smtp = new Smtp())              // Connect to SMTP server
            {
                smtp.Connect(_server);                  // Use overloads or ConnectSSL if you need to specify different port or SSL.
                smtp.UseBestLogin(_user, _password);    // You can also use: Login, LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                                                        // or use UseBestLogin method if you want Mail.dll to choose for you.

                SendMessageResult result = smtp.SendMessage(email);
                Console.WriteLine(result.Status);

                smtp.Close();
            }
        }
        public IActionResult GetEmailControlCode(EmailRegistration emailCancell)
        {
            string postResultString;
            int    messageNumber;
            var    emailCancelled = emailRegRepository.GetAll().Where(p => p.EmailAddress == emailCancell.EmailAddress);

            if (emailCancelled.Any())
            {
                if (ModelState.IsValid)
                {
                    var    setting     = settingRepository.GetById(1);
                    string messageHtml = "" +
                                         "<div style='background-color:#F7F7F7;padding:5px;'>" +
                                         "<div style='background-color:#FFF;padding:5px;'>" +
                                         "<p>Kontrol Kodunuz: " + emailCancelled.First().ControlCode + "</p>" +
                                         "</div>" +
                                         "</div>";

                    MailBuilder builder = new MailBuilder();

                    builder.From.Add(new MailBox(setting.SMTPServerFrom, setting.SMTPServerFromName));
                    builder.To.Add(new MailBox(emailCancell.EmailAddress));

                    builder.Subject = "Abonelik İptali İçin Kontrol Kodu";
                    builder.Html    = messageHtml;

                    IMail email = builder.Create();

                    using Smtp smtp = new Smtp();
                    smtp.Connect(setting.SMTPServerHost, Convert.ToInt32(setting.SMTPServerPort)); // or ConnectSSL for SSL
                    smtp.UseBestLogin(setting.SMTPServerUsername, setting.SMTPServerPassword);     // remove if not needed
                    smtp.SendMessage(email);
                    smtp.Close();

                    postResultString = "Kontrol kodu, e-posta adresinize gönderildi.";
                    messageNumber    = 2;
                }
                else
                {
                    postResultString = "Kontrol kodu gönderilirken bir hata oluştu! Lütfen daha sonra tekrar deneyiniz veya iletişime geçiniz.";
                    messageNumber    = 3;
                }
            }
            else
            {
                postResultString = "Girilen e-posta adresi için bir kayıt bulunamadı! Lütfen doğru bilgileri girdiğinizden emin olunuz.";
                messageNumber    = 1;
            }

            return(new JsonResult(new { message = postResultString, messageType = messageNumber }));
        }
Example #9
0
        public void SendEmail(string _attachment)
        {
            var setup = new Setup();

            setup.SetBackupProperties(System.IO.Directory.GetCurrentDirectory() + "\\config.ini");
            IMail email = Mail
                          .Html(@"Html ")
                          .AddAttachment(_attachment).SetFileName("bugreport.txt")
                          .To(setup.GetMailReceiver())
                          .From(setup.GetMailFrom())
                          .Subject("Database backup bugreport")
                          .Create();

            using (Smtp smtp = new Smtp())
            {
                smtp.Connect(setup.GetSmtpServer());  // or ConnectSSL for SSL
                smtp.UseBestLogin(setup.GetSmtpLogin(), setup.GetSmtpPass());
                smtp.SendMessage(email);
                smtp.Close();
            }
        }
Example #10
0
        /// <summary>
        /// Uses SMTP to send an email through Mail.dll with the paramenters below. Returns whether it sent successfully
        /// </summary>
        /// <param name="HostServer"></param>
        /// <param name="HostUName"></param>
        /// <param name="HostPass"></param>
        /// <param name="SpoofFrom"></param>
        /// <param name="SpoofName"></param>
        /// <param name="ToAddress"></param>
        /// <param name="Subject"></param>
        /// <param name="Body"></param>
        /// <returns></returns>
        public bool SendEmail(string HostServer, string HostUName, string HostPass, string SpoofFrom, string SpoofName, string ToAddress, string Subject, string Body)
        {
            //The following 5 lines set up the email itself.
            MailBuilder Builder = new MailBuilder();

            Builder.From.Add(new MailBox(SpoofFrom, SpoofName));
            Builder.To.Add(new MailBox(ToAddress));
            Builder.Subject = Subject;
            Builder.Html    = Body;

            //The following section creates the email and then sends the email
            IMail Email = Builder.Create();

            using (Smtp smtp = new Smtp())
            {
                //the next three lines defines a local variable and then logs into mail server. For security reasons
                //I have omitted the password from the login line.
                bool Success;
                smtp.ConnectSSL(HostServer);
                smtp.UseBestLogin(HostUName, HostPass);

                //This section attempts to send the email and returns whether it manages to send an email successfully.
                SendMessageResult Result = smtp.SendMessage(Email);
                if (Result.Status == SendMessageStatus.Success)
                {
                    Success = true;
                }
                else
                {
                    Success = false;
                }

                smtp.Close();
                return(Success);
            }
        }
Example #11
0
        /// <summary> Spedisce l'email. </summary>
        /// <param name="mailbox"> MailBox da dove spedire l'email. </param>
        /// <param name="email"> Email da spedire. </param>
        /// <param name="pecMail"> PEC da inviare </param>
        /// <param name="guid"> Guid della mail</param>
        public bool SendMail(PECMailBox mailbox, IMail email, PECMail pecMail, Guid guid, string password)
        {
            // In caso di modalità DEBUG modifico i destinatari con quello di default:
            if (_parameters.DebugModeEnabled)
            {
                // Creo una nuova mail alla quale aggiungo come allegato la mail originale
                MailBuilder debugBuilder = new MailBuilder();
                debugBuilder.From.Add(email.From.First());

                debugBuilder.Subject = string.Format("Inoltro messaggio per DEBUG -> {0}", email.Subject);

                // Crea il corpo del messaggio di default (non è richiesto dall'Interoperabilità) o lo legge da base dati, se indicato
                debugBuilder.Text = "In allegato la mail che sarebbe stata spedita.";

                // Aggiungo il destinatario di debug
                debugBuilder.To.Add(new MailBox(_parameters.PecOutAddressDebugMode, "DEBUG ADDRESS"));

                // Aggiungo la mail come allegatos
                debugBuilder.AddAttachment(email);

                // Sostituisco item con il debugMail
                email = debugBuilder.Create();

                FileLogger.Info(_loggerName, string.Format("Modificato l'indirizzo di invio della PEC con l'indirizzo {0}.", _parameters.PecOutAddressDebugMode));
            }

            // Eseguo in modo atomico il blocco di invio
            int  i    = 0;
            bool sent = false;
            ISendMessageResult sendResult    = null;
            Exception          lastException = null;

            while (!sent && i < 5)
            {
                try
                {
                    using (Smtp smtp = new Smtp())
                    {
                        smtp.ServerCertificateValidate += ServerCertificateValidateHandler;

                        // Utilizzo connessione SSL
                        if (mailbox.OutgoingServerUseSsl.HasValue && mailbox.OutgoingServerUseSsl.Value)
                        {
                            smtp.SSLConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                            smtp.ConnectSSL(mailbox.OutgoingServerName, mailbox.OutgoingServerPort.HasValue ? mailbox.OutgoingServerPort.Value : 465);
                        }
                        else
                        {
                            smtp.Connect(mailbox.OutgoingServerName, mailbox.OutgoingServerPort.HasValue ? mailbox.OutgoingServerPort.Value : 25);
                        }

                        // Utilizzo autenticazione
                        if (!string.IsNullOrEmpty(mailbox.Username) && !string.IsNullOrEmpty(password))
                        {
                            smtp.UseBestLogin(mailbox.Username, password);
                        }

                        sendResult = smtp.SendMessage(email);
                        sent       = (sendResult.Status == SendMessageStatus.Success);
                        if (!sent)
                        {
                            string errors = string.Empty;
                            if (sendResult.GeneralErrors != null && sendResult.GeneralErrors.Any())
                            {
                                errors = string.Join(", ", sendResult.GeneralErrors
                                                     .Select(f => string.Concat("Code: ", f.Code, " - EnhancedStatusCode: ", f.EnhancedStatusCode, " - Message: ", f.Message, " - Status : ", f.Status)));
                            }
                            FileLogger.Error(_loggerName, string.Format("Errore in spedizione PEC {0} / casella {1} - {2}. Stato spedizione: {3} - Errori:{4}.", pecMail.Id, mailbox.Id, mailbox.MailBoxName, sendResult.Status, errors));
                        }
                        smtp.Close(false);
                    }

                    if (!sent)
                    {
                        continue;
                    }

                    // Aggiorno immediatamente la PEC come spedita in modo da non avere dubbi che la PEC sia stata davvero spedita
                    pecMail.MailDate = DateTime.Now;
                    pecMail.XRiferimentoMessageID = string.Format("<{0}>", guid);
                    _factory.PECMailFacade.UpdateOnly(ref pecMail);
                    Protocol currentProtocol = _factory.PECMailFacade.GetProtocol(pecMail);
                    if (currentProtocol != null && (short)ProtocolKind.FatturePA == currentProtocol.IdProtocolKind)
                    {
                        currentProtocol.IdStatus = (int)ProtocolStatusId.PAInvoiceSent;
                        _factory.ProtocolFacade.UpdateOnly(ref currentProtocol);
                    }
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    // Se mi trovo in questo status è avvenuto un errore in fase di spedizione, per cui posso riprocedere ad inviare
                    FileLogger.Error(_loggerName, string.Format("Non è stato possibile inviare la PEC {0} / casella {1} - {2} per un probabile errore di rete o di server PEC. La procedura verrà ritentata. - Tentativo {3}/5", pecMail.Id, mailbox.Id, mailbox.MailBoxName, i + 1), ex);
                    // Attendo 1 minuto prima di riprovare
#if !DEBUG
                    Thread.Sleep(1000 * 30);
#endif
                }
                finally
                {
                    // Procedo
                    i++;
                }
            }

            // Se dopo 5 tentativi ancora non ha ricevuto conferma di spedizione allora invio una mail e blocco l'invio
            if (sent)
            {
                _factory.PECMailboxLogFacade.SentMail(ref pecMail);
                return(true);
            }
            // Errori
            String errorMessages = string.Format("Errori di invio:{0}", Environment.NewLine);
            errorMessages = sendResult.GeneralErrors.Aggregate(errorMessages, (current, generalError) => current + string.Format("Code:{1} - Message:{2} - Status:{3}{0}", Environment.NewLine, generalError.Code, generalError.Message, generalError.Status));
            _factory.PECMailboxLogFacade.SentErrorMail(ref pecMail, new Exception(errorMessages));

            pecMail.IsActive = ActiveType.Cast(ActiveType.PECMailActiveType.Error);
            _factory.PECMailFacade.UpdateOnly(ref pecMail);
            String errorResult = string.Format("La PEC {0} / casella {1} - {2} non è stata spedita dopo 5 tentativi falliti. \nE' stata pertanto disattivata (isActive = 255) per evitare ulteriori tentativi.", pecMail.Id, mailbox.Id, mailbox.MailBoxName);
            _factory.PECMailLogFacade.Error(ref pecMail, errorResult);
            _factory.PECMailLogFacade.Error(ref pecMail, string.Concat(errorResult, errorMessages));
            MailStoreFacade.SetPECMailTaskError(pecMail);
            throw new Exception(errorResult, lastException);
        }
Example #12
0
        private void sendMail(Message _message)
        {
            if (_message == null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Server))
            {
                return;
            }

            Logger.WriteDebug(MethodBase.GetCurrentMethod(), "Start to send mail");

            //Check settings
            if (Settings.Default.MailOutput_Port <= 0)
            {
                throw new ArgumentNullException("MailOutput_Port");
            }

            if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Sender))
            {
                throw new ArgumentNullException("MailOutput_Sender");
            }

            if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_User))
            {
                throw new ArgumentNullException("MailOutput_User");
            }

            if (string.IsNullOrWhiteSpace(Settings.Default.MailOutput_Password))
            {
                throw new ArgumentNullException("MailOutput_Password");
            }

            //Settings
            var _senderMailbox = new MailBox(Settings.Default.MailOutput_Sender, "Rescue-Information-System");
            var _mailBuilder   = new MailBuilder();

            _mailBuilder.From.Add(_senderMailbox);
            _mailBuilder.Subject = _message.Subject;
            _mailBuilder.Text    = _message.Text;
            //Werbung
            for (var i = 0; i < 5; i++)
            {
                _mailBuilder.Text += Environment.NewLine;
            }

            _mailBuilder.Text += "RIS by www.srs-software.de";

            //Empfänger hinzufügen
            foreach (var _user in _message.Recivers)
            {
                if (!isValidEmail(_user.MailAdresse))
                {
                    Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"User {_user.Name} -> mail address not valid");
                    continue;
                }

                var _newAdress = new MailBox(_user.MailAdresse, _user.Name);
                _mailBuilder.Bcc.Add(_newAdress);
                Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"User add ({_user.Name})");
            }

            if (_mailBuilder.Bcc.Count <= 0)
            {
                Logger.WriteDebug(MethodBase.GetCurrentMethod(), "cancel no recipients");
                return;
            }

            //Anhang
            if (!string.IsNullOrEmpty(_message.AttachmentPath))
            {
                if (File.Exists(_message.AttachmentPath) && WaitFileReady.Check(_message.AttachmentPath))
                {
                    _mailBuilder.AddAttachment(_message.AttachmentPath);
                }
                else
                {
                    Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"{_message.AttachmentPath} -> not found");
                }
            }

            //send mail
            Logger.WriteDebug(MethodBase.GetCurrentMethod(), "start sending");
            using (var _smtpClient = new Smtp())
            {
                if (Settings.Default.MailOutput_SSL)
                {
                    _smtpClient.ConnectSSL(Settings.Default.MailOutput_Server, Settings.Default.MailOutput_Port);
                }
                else
                {
                    _smtpClient.Connect(Settings.Default.MailOutput_Server, Settings.Default.MailOutput_Port);
                    if (_smtpClient.SupportedExtensions().Contains(SmtpExtension.StartTLS))
                    {
                        _smtpClient.StartTLS();
                    }
                }

                _smtpClient.UseBestLogin(Settings.Default.MailOutput_User,
                                         Encrypt.DecryptString(Settings.Default.MailOutput_Password, "MailOutput_Password"));
                Logger.WriteDebug(MethodBase.GetCurrentMethod(), "login -> ok");

                var _mail = _mailBuilder.Create();
                _mail.PriorityHigh();
                var _result = _smtpClient.SendMessage(_mail);

                Logger.WriteDebug(MethodBase.GetCurrentMethod(), $"result -> {_result}");
                _smtpClient.Close();
            }

            Logger.WriteDebug(MethodBase.GetCurrentMethod(), "send mail finished");
        }
Example #13
0
        private void startprocess(string logindetails, string imapselect, bool sendmail, string smtptet)
        {
            try
            {
                int    type   = 0;
                Socket socket = null;

                if (proxies.Count > 0)
                {
                    type = 1;
                    ProxyFactory factory = new ProxyFactory();
                    string       proxi   = proxies[rad.Next(proxies.Count)];
                    string[]     prox    = proxi.Split(':');
                    IProxyClient proxy   = null;
                    if (prox.Length == 4)
                    {
                        proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]);
                    }
                    else
                    {
                        proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]));
                    }
                    socket = proxy.Connect(imapselect, Imap.DefaultSSLPort);
                }
                using (Imap imap = new Imap())
                {
                    if (type == 0)
                    {
                        imap.ConnectSSL(imapselect);
                    }
                    else
                    {
                        imap.AttachSSL(socket, imapselect);
                    }
                    string[] cred = logindetails.Split(':');
                    imap.Login(cred[0], cred[1]);                   // You can also use: LoginPLAIN, LoginCRAM, LoginDIGEST, LoginOAUTH methods,
                    CommonFolders folders = new CommonFolders(imap.GetFolders());
                    imap.Select(folders.Spam);
                    foreach (long ouid in imap.GetAll())
                    {
                        IMail email = new MailBuilder().CreateFromEml(
                            imap.GetMessageByUID(ouid));

                        List <long> unseenReports = new List <long>();
                        foreach (string sub in subjects)
                        {
                            if (email.Subject.Contains(sub) || string.Equals(email.Subject, sub))
                            {
                                unseenReports.Add(ouid);

                                if (!checkBox1.Checked && sendmail && !radioButton4.Checked)
                                {
                                    IMail  original = email;
                                    Socket socket1  = null;
                                    if (proxies.Count > 0)
                                    {
                                        type = 1;
                                        ProxyFactory factory = new ProxyFactory();
                                        string       proxi   = proxies[rad.Next(proxies.Count)];
                                        string[]     prox    = proxi.Split(':');
                                        IProxyClient proxy   = null;
                                        if (prox.Length == 4)
                                        {
                                            proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]), prox[2], prox[3]);
                                        }
                                        else
                                        {
                                            proxy = factory.CreateProxy(ProxyType.Http, prox[0], Convert.ToInt32(prox[1]));
                                        }
                                        socket1 = proxy.Connect(smtptet, portsmtp);
                                    }
                                    ReplyBuilder replyBuilder = original.Reply();

                                    // You can specify your own, custom, body and subject templates:
                                    replyBuilder.HtmlReplyTemplate    = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
    <html>
    <head>
        <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" />
        <title>[Subject]</title>
    </head>
    <body>
    [Html]
    <br /><br />
    On [Original.Date] [Original.Sender.Name] wrote:
    <blockquote style=""margin-left: 1em; padding-left: 1em; border-left: 1px #ccc solid;"">
        [QuoteHtml]
    </blockquote>
    </body>
    </html>";
                                    replyBuilder.SubjectReplyTemplate = "Re: [Original.Subject]";

                                    replyBuilder.Html = NewSpin.Spin(textBox1.Text);

                                    MailBuilder builder = replyBuilder.ReplyToAll(cred[0]);

                                    // You can add attachments to your reply
                                    //builder.AddAttachment("report.csv");

                                    IMail reply = builder.Create();
                                    using (Smtp smtp = new Smtp())
                                    {
                                        if (type == 0)
                                        {
                                            if (radioButton3.Checked || radioButton4.Checked)
                                            {
                                                smtp.Connect(smtptet, portsmtp);
                                                smtp.StartTLS();
                                            }
                                            else
                                            {
                                                smtp.ConnectSSL(smtptet, portsmtp);
                                            }
                                        }
                                        else
                                        {
                                            if (radioButton3.Checked || radioButton4.Checked)
                                            {
                                                smtp.Attach(socket1);
                                                smtp.StartTLS();
                                            }
                                            else
                                            {
                                                smtp.AttachSSL(socket1, smtptet);
                                            }
                                        }
                                        smtp.ReceiveTimeout = new TimeSpan(0, 0, 100);
                                        //MessageBox.Show("Sending Mail");
                                        smtp.UseBestLogin(cred[0], cred[1]);
                                        smtp.SendMessage(reply);
                                        smtp.Close();
                                    }
                                }
                            }
                        }

                        foreach (long uid in unseenReports)        // Download emails from the last result.
                        {
                            // MessageBox.Show(uid.ToString());
                            imap.MoveByUID(uid, folders.Inbox);

                            imap.FlagMessageByUID(uid, Flag.Seen);
                            movedcount = movedcount + 1;
                        }
                    }
                    imap.Close();
                }
            }
            catch (Exception exp)
            {
                //MessageBox.Show(exp.ToString());
            }
            finally
            {
                count = count + 1;
            }
        }
Example #14
0
        public byte[] Send(MailMessage message, bool returnBlob = false, bool needDispositionNotification = false, StandardMailAddress notificationTo = null)
        {
            // Gestore dei messaggi
            MailBuilder builder = new MailBuilder {
                MessageID = Guid.NewGuid().ToString(), Subject = message.Subject
            };

            // Creo il messaggio base
            builder.From.Add(new MailBox(message.From.Address, message.From.DisplayName));
            builder.Text = message.Body;
            builder.Html = message.Body.Replace(Environment.NewLine, "<br />");

            // Carico i destinatari A
            foreach (var recipient in message.To)
            {
                builder.To.Add(new MailBox(recipient.Address, recipient.DisplayName));
            }

            // Carico i destinatari CC
            foreach (var recipient in message.CC)
            {
                builder.Cc.Add(new MailBox(recipient.Address, recipient.DisplayName));
            }

            //Specifico se notificare al mittente la notifiche di lettura e ricezione
            if (needDispositionNotification && notificationTo != null)
            {
                MailBox originalSender = new MailBox(notificationTo.Address, notificationTo.DisplayName);
                builder.RequestReadReceipt();
                builder.NotificationTo.Clear();
                builder.ReplyTo.Clear();
                builder.ReturnReceiptTo.Clear();
                builder.NotificationTo.Add(originalSender);
                builder.ReturnReceiptTo.Add(originalSender);
            }

            // Carico gli allegati
            foreach (var attachment in message.Attachments)
            {
                var mime = new MimeFactory().CreateMimeData();
                using (var ms = new MemoryStream())
                {
                    attachment.ContentStream.CopyTo(ms);
                    mime.Data = ms.ToArray();
                }

                mime.ContentType = ContentType.Parse(attachment.Name.GetMimeType());
                mime.FileName    = attachment.Name;
                builder.AddAttachment(mime);
            }

            // Priorità
            switch (message.Priority)
            {
            case MailPriority.Low:
                builder.Priority = MimePriority.NonUrgent;
                break;

            case MailPriority.Normal:
                builder.Priority = MimePriority.Normal;
                break;

            case MailPriority.High:
                builder.Priority = MimePriority.Urgent;
                break;
            }

            // Genero la mail da spedire
            var email = builder.Create();

            var       sent          = false;
            var       i             = 0;
            Exception lastException = null;

            while (!sent && i < 5)
            {
                using (var smtp = new Smtp())
                {
                    // Accetto anche i certificati non validi
                    smtp.ServerCertificateValidate += ServerCertificateValidateCallBack;

                    // Connessione al server
                    smtp.Connect(_server, _port, AuthenticationType == MailClient.AuthenticationType.Ssl);

                    // Attivazione Tls, se richiesta
                    if (AuthenticationType == MailClient.AuthenticationType.Tls)
                    {
                        smtp.StartTLS();
                    }

                    // Login, se necessario
                    if (!UseDefaultCredentials)
                    {
                        smtp.UseBestLogin(Credentials.UserName, Credentials.Password);
                    }

                    // Imposto il timeout per la richiesta
                    smtp.SendTimeout = new TimeSpan(0, 0, 0, 0, Timeout);

                    // Invio e calcolo il risultato
                    var messageResult = smtp.SendMessage(email);
                    sent = (messageResult.Status == SendMessageStatus.Success);
                    try
                    {
                        smtp.Close(true);
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                    }
                }

                if (!sent)
                {
                    Thread.Sleep(1000 * 30);
                    continue;
                }
                i++;
            }

            if (returnBlob && email != null)
            {
                byte[] eml = email.Render();
                return(eml);
            }

            if (!sent && lastException != null)
            {
                throw new Exception("Impossibile inviare il messaggio dopo 5 tentativi.", lastException);
            }

            return(null);
        }