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

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

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

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

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

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

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

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

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

            await dlg.ShowAsync();



        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            if (User.IsInRole("Administrateur") == false)
            {
                SmtpServer serveur = SmtpServer.Get(SessionState.MemberInfo.MembreGUID);
                if (serveur != null)
                {
                    TextBoxUserName.Text      = serveur.UserName;
                    TextBoxPassWord.Text      = serveur.UserPassWord;
                    TextBoxServerName.Text    = serveur.ServerName;
                    TextBoxServerPort.Text    = serveur.ServerPort.ToString();
                    TextBoxEmail.Text         = serveur.Email;
                    TextBoxEmailSubject.Text  = serveur.EmailSubject;
                    CheckBoxEnableSSL.Checked = serveur.EnableSSL;
                    // FCKeditor1.Value = serveur.EmailBody; ne sert plus c'est une WebContent CorpsEmail
                }
                else
                {
                    TextBoxServerPort.Text = "25";
                }
            }
            else
            {
                PanelAdmin.Visible = true;
                //TextBoxUserName.Enabled = false;
            }
        }

        MessageValidation(string.Empty);
        Page.MaintainScrollPositionOnPostBack = true;
    }
Example #3
0
        public void TestOne()
        {
            EmailMessage emailmessage = new EmailMessage();

            emailmessage.FromAddress = TestAddressHelper.GetFromAddress();

            emailmessage.AddToAddress(TestAddressHelper.GetToAddress());

            emailmessage.Subject = "Missed you";

            emailmessage.TextPart = new TextAttachment("Just checking where " +
                                                       "you were last night.\r\nSend me a note!\r\n\r\n-Charles");

            emailmessage.HtmlPart = new HtmlAttachment("<html><body>" +
                                                       "<p>Just checking up on where you were last night.</p>\r\n" +
                                                       "<p>Send me a note!</p>\r\n\r\n" +
                                                       "<p>-Charles</p></body></html>");

            SmtpServer smtpserver = TestAddressHelper.GetSmtpServer();

            //smtpserver.CaptureSmtpConversation=true;

            try
            {
                emailmessage.Send(smtpserver);
            }
            finally
            {
                //log.Debug(smtpserver.GetSmtpConversation());
                //Assert.IsNotNull(smtpserver.GetSmtpConversation());
                //smtpserver.CaptureSmtpConversation=false;
            }
        }
        public void SendMailToUserByNumberOfParking(int numberOfParking, string message)
        {
            SmtpServer server = new SmtpServer("smtp.gmail.com", 465);

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

            string userEmail = (from c in ctx.Users
                                join p in ctx.ParkingPlaces
                                on c.Id equals p.UserId
                                select c.Email).Single();

            if (userEmail != null)
            {
                SmtpClient client = new SmtpClient();

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

                client.SendMail(server, letter);
            }
        }
 void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     for (int i = 0; i < ListView_addresses.Items.Count; i++)
     {
         try
         {
             //ListView_addresses.Items[i].Selected = true;
             ///////////////////////////////
             //the code for smtp properties
             //////////////////////////////
             SmtpServer.Send(mail);
             //ListView_addresses.Items[i].Checked = true;
             ((BackgroundWorker)sender).ReportProgress(0, new SmtpResult {
                 Index = i, Checked = true, Selected = true
             });
         }
         catch
         {
             ListView_addresses.Items[i].Checked = false;
             ((BackgroundWorker)sender).ReportProgress(0, new SmtpResult {
                 Index = i, Checked = false, Selected = true
             });
         }
     }
 }
        public void EnviarCorreo(string correoDestino, string asunto, string mensajeCorreo)
        {
            string mensaje = "Error al enviar correo.";

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

                objetoCorreo.From     = "*****@*****.**";
                objetoCorreo.To       = correoDestino;
                objetoCorreo.Subject  = asunto;
                objetoCorreo.TextBody = mensajeCorreo;

                SmtpServer objetoServidor = new SmtpServer("smtp.gmail.com");//servidor proporcionado desde la configuracion de google

                objetoServidor.User        = "******";
                objetoServidor.Password    = "******";
                objetoServidor.Port        = 587;
                objetoServidor.ConnectType = SmtpConnectType.ConnectSSLAuto;

                SmtpClient objetoCliente = new SmtpClient();
                objetoCliente.SendMail(objetoServidor, objetoCorreo);
                mensaje = "Correo Enviado Correctamente.";
            }
            catch (Exception ex)
            {
                mensaje = "Error al enviar correo." + ex.Message;
            }
        }
Example #7
0
        private SmtpServer _createSmtpServer()
        {
            SmtpServer server = new SmtpServer(TextBoxServer.Text);

            server.Protocol = (ServerProtocol)ComboBoxProtocols.SelectedIndex;

            // If remote SMTP server supports TLS, then use TLS, otherwise use plain TCP/IP.
            server.ConnectType = SmtpConnectType.ConnectTryTLS;

            if (server.Server.Length != 0)
            {
                int[] ports = { 25, 587, 465 };
                server.Port = ports[ComboBoxPorts.SelectedIndex];

                if (CheckBoxAuth.Checked)
                {
                    server.User     = TextBoxUser.Text;
                    server.Password = TextBoxPassword.Text;
                }

                if (CheckBoxSsl.Checked)
                {
                    server.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }
            }

            return(server);
        }
Example #8
0
        private static void SendMailWithXOAUTH2(string email, string subject, string textBody, string accessToken)
        {
            try
            {
                string userEmail = "*****@*****.**";
                // string userPassword = "******";

                SmtpServer oServer = new SmtpServer("smtp.gmail.com", 587); // 465 can be used too
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                oServer.AuthType = SmtpAuthType.XOAUTH2;
                oServer.User     = userEmail;
                // use access token as password
                oServer.Password = accessToken;

                SmtpMail oMail = new SmtpMail("TryIt");
                // Your gmail email address
                oMail.From = userEmail;
                oMail.To   = email;

                oMail.Subject  = subject;
                oMail.TextBody = textBody;

                EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
                oSmtp.SendMail(oServer, oMail);
            }
            catch (Exception ep)
            {
                Console.WriteLine("Exception: {0}", ep.Message);
            }
        }
    // Copier le serveur SMTP de l'intervieweur pour l'utilisateur
    public void ButtonCopier_OnClick(object sender, EventArgs e)
    {
        SmtpServer serveur    = new SmtpServer();
        Guid       membreGUID = new Guid();
        MemberInfo member     = MemberInfo.GetMemberInfo("Intervieweur");

        serveur    = SmtpServer.Get(member.MembreGUID);
        membreGUID = member.MembreGUID;

        if (serveur == null)   // pas de serveur SMTP de l'Intervieweur
        {
            ValidationMessage.Text = "Il n'y pas de serveur SMTP de test configuré";
        }
        else
        {
            TextBoxUserName.Text      = serveur.UserName;
            TextBoxPassWord.Text      = serveur.UserPassWord;
            TextBoxServerName.Text    = serveur.ServerName;
            TextBoxServerPort.Text    = serveur.ServerPort.ToString();
            TextBoxEmail.Text         = serveur.Email;
            TextBoxEmailSubject.Text  = serveur.EmailSubject;
            CheckBoxEnableSSL.Checked = serveur.EnableSSL;
            ValidationMessage.Text    = "Cliquez sur \"Sauver\" pour conserver ce serveur SMTP";
        }
        PanelMessageValidation.Visible = true;
    }
Example #10
0
        public void send_email()
        {
            SmtpMail   oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

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

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

            // Set email subject
            oMail.Subject = "test email";

            // Set email body
            oMail.TextBody = "I HOPE YOU GET";

            // If your account is office 365, please change to Office 365 SMTP server
            SmtpServer oServer = new SmtpServer("smtp.office365.com");

            // User authentication should use your
            // email address as the user name.
            oServer.User     = "******";
            oServer.Password = "";

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

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

            oSmtp.SendMail(oServer, oMail);
        }
Example #11
0
        public void SendEMail(Request request)
        {
            SmtpMail   oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

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

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

            // Set email subject
            oMail.Subject = $"درخواست تعمیر {request.ApplicationType.GetDescription()}";


            string message = $"نام : {request.Name} | تلفن : {request.Phone} | آدرس: {request.Address} | موضوع پیام : {request.ApplicationType.GetDescription()} | زمان درخواست : {DateTime.Now.CurrentDate("fa-IR")}";

            // Set email body
            oMail.TextBody = message;

            // Your SMTP server address
            SmtpServer oServer = new SmtpServer("webmail.dinaservice.com")
            {
                // User and password for ESMTP authentication, if your server doesn't require
                // User authentication, please remove the following codes.
                User     = "******",
                Password = "******",

                // some SMTP servers uses 587 port, you can change it to 587
                Port = 587
            };

            oSmtp.SendMail(oServer, oMail);
        }
Example #12
0
        public void SendAuthorForgotPasswordEmail(Author author, string email)
        {
            SmtpMail   oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            oMail.From = "*****@*****.**";

            oMail.To = email;

            oMail.Subject = "بازیابی رمز - عبور رمان فارسی";


            StringBuilder message = new StringBuilder();

            message.AppendLine("با سلام");
            message.AppendLine($"این ایمیل صرفا جهت بازیابی رمز عبور {author.FirstName} {author.LastName} ارسال شده است . در صورتی که این ایمیل برای شمما نیست لطفا آن را حذف نمایید");
            message.AppendLine($"جهت بازیابی رمز عبور بر روی این لینک کلیک نمایید {OrginUrl}/Author/ForgotReturnPage/{author.Id}");
            oMail.TextBody = message.ToString();

            SmtpServer oServer = new SmtpServer("webmail.persiannovel.com")
            {
                User     = "******",
                Password = "******",
                Port     = 587
            };

            oSmtp.SendMail(oServer, oMail);
        }
Example #13
0
        public void SendEmail(string subject, string body, string email)
        {
            SmtpMail mail = new SmtpMail("TryIt");

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

            // Set recipient email address
            mail.To = email;

            // Set email subject
            mail.Subject = subject;

            // Set email body
            mail.HtmlBody = body;

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

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

            // set 587 SSL port
            server.Port = 465;

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

            SmtpClient oSmtp = new SmtpClient();

            oSmtp.SendMail(server, mail);
        }
Example #14
0
        internal static void TestSmtp(SmtpServer smtp, string ToEmail, string FriendlyName, string FromEmail, string FromName, string ReplyTo, ref string SuccessfulMessage, ref string ExceptionsMessage)
        {
            try
            {
                if (smtp != null && !string.IsNullOrEmpty(ToEmail) && !string.IsNullOrEmpty(FromEmail) && !string.IsNullOrEmpty(FromName))
                {
                    SmtpClient client = Connect(smtp.Server, smtp.Port, smtp.Authentication, smtp.Username, smtp.Password, smtp.SSL);

                    var msg = new MailQueue
                    {
                        FromName   = FromEmail,
                        FromEmail  = FromEmail,
                        ToEmail    = ToEmail,
                        ReplyEmail = ReplyTo,
                        Subject    = !string.IsNullOrEmpty(FriendlyName) ? FriendlyName + " Notification Email SMTP Configuration Test" : "Notification Email SMTP Configuration Test",
                    };

                    SendMail(client, msg);

                    SuccessfulMessage = "Email Sent Successfully from " + FromEmail.Trim().ToLower() + " to " + ToEmail.Trim().ToLower();
                }
            }
            catch (Exception ex)
            {
                ExceptionsMessage += "<br />" + ex.Message;
            }
        }
        public void EnviarCorreo(string correoDestino, string asunto, string mensajeCorreo)
        {
            string mensaje = "Error al enviar correo.";

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

                objetoCorreo.From     = "*****@*****.**";
                objetoCorreo.To       = correoDestino;
                objetoCorreo.Subject  = asunto;
                objetoCorreo.TextBody = mensajeCorreo;

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

                objetoServidor.User        = "******";
                objetoServidor.Password    = "******";
                objetoServidor.Port        = 587;
                objetoServidor.ConnectType = SmtpConnectType.ConnectSSLAuto;

                SmtpClient objetoCliente = new SmtpClient();
                objetoCliente.SendMail(objetoServidor, objetoCorreo);
                mensaje = "Correo Enviado Correctamente.";
            }
            catch (Exception ex)
            {
                mensaje = "Error al enviar correo." + ex.Message;
            }
        }
Example #16
0
        public void CanReceive8BitMimeMessage()
        {
            // arrange
            var smtpServer     = new SmtpServer(_optionsBuilder.Build());
            var smtpClient     = new SmtpClient();
            var smtpServerTask = smtpServer.StartAsync(_cancellationTokenSource.Token);

            var message = new MimeKit.MimeMessage();

            message.From.Add(new MailboxAddress("*****@*****.**"));
            message.To.Add(new MailboxAddress("*****@*****.**"));
            message.Subject = "Assunto teste acento çãõáéíóú";
            message.Body    = new TextPart("plain")
            {
                Text = "Assunto teste acento çãõáéíóú"
            };

            // act
            smtpClient.Connect("localhost", 25, false);
            smtpClient.Send(message);

            // assert
            Assert.Equal(1, _messageStore.Messages.Count);

            Wait(smtpServerTask);
        }
        bool SendMail(string email, string body)
        {
            SmtpMail   oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            oMail.From     = "*****@*****.**";
            oMail.To       = email;
            oMail.Subject  = "Failure of completion of Task on time";
            oMail.TextBody = body;
            SmtpServer oServer = new SmtpServer("smtp.gmail.com");

            oServer.Port        = 587;
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            oServer.User        = "******";
            oServer.Password    = "******";

            try
            {
                oSmtp.SendMail(oServer, oMail);
                return(true);
            }
            catch (Exception ep)
            {
                MessageBox.Show("Failed to send mail, Error : " + ep);
                return(false);
            }
        }
Example #18
0
        public static void SendMailUsingoffice365(string EmailAddress, string AccessToken, string ToMailAddress, string EmailSubject, string MailBody)
        {
            // Office365 server address
            SmtpServer oServer = new SmtpServer("outlook.office365.com");

            // Using 587 port, you can also use 465 port
            oServer.Port = 587;
            // enable SSL connection
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            // use SMTP OAUTH 2.0 authentication
            oServer.AuthType = SmtpAuthType.XOAUTH2;
            // set user authentication
            oServer.User = EmailAddress;
            // use access token as password
            oServer.Password = AccessToken;

            SmtpMail oMail = new SmtpMail("TryIt");

            // Your email address
            oMail.From = EmailAddress;

            // Please change recipient address to yours for test
            oMail.To = ToMailAddress;

            oMail.Subject  = EmailSubject;
            oMail.TextBody = MailBody;

            Console.WriteLine("start to send email using OAUTH 2.0 ...");

            EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
            oSmtp.SendMail(oServer, oMail);
        }
Example #19
0
        public static void SendMailAccessToken(string FromEmailAddress, string accessToken, string ToEmailAddress, string Subject, string Body)
        {
            // Gmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.gmail.com");

            // enable SSL connection
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            // Using 587 port, you can also use 465 port
            oServer.Port = 587;

            // use Gmail SMTP OAUTH 2.0 authentication
            oServer.AuthType = SmtpAuthType.XOAUTH2;
            // set user authentication
            oServer.User = FromEmailAddress;
            // use access token as password
            oServer.Password = accessToken;

            SmtpMail oMail = new SmtpMail("TryIt");

            // Your gmail email address
            oMail.From = FromEmailAddress;
            oMail.To   = ToEmailAddress;

            oMail.Subject  = Subject;
            oMail.HtmlBody = Body;
            //oMail.TextBody = Body;

            EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
            oSmtp.SendMail(oServer, oMail);
        }
 public BandwidthLogger(SmtpServer server)
 {
     Debug.WriteLine(logPrefix + "Agent constructor");
     this.server              = server;
     this.OnSubmittedMessage += SubmittedMessage;
     this.OnRoutedMessage    += RoutedMessage;
 }
Example #21
0
        private void loadAcceptedDomains(SmtpServer server)
        {
            try
            {
                if (htAcceptedDomains == null)
                {
                    this.htAcceptedDomains = new Hashtable();
                }
                else
                {
                    this.htAcceptedDomains.Clear();
                }

                foreach (AcceptedDomain domain in server.AcceptedDomains)
                {
                    htAcceptedDomains.Add(domain.ToString().ToLower(), "1");
                    WriteLine("\tAccepted Domain: " + domain.ToString().ToLower());
                }
            }
            catch (Exception ex)
            {
                WriteLine("\t[Error] " + ex.Message);
                LogErrorToEventLog("[Error] [loadAcceptedDomains] Error :" + ex.Message);
            }
        }
        static void Main(string[] args)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

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

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

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

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

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

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

            try
            {
                Console.WriteLine("start to send email directly ...");
                oSmtp.SendMail(oServer, oMail);
                Console.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
            }
        }
Example #23
0
        public bool EnviarNotificacionEmailOutlook(EstructuraMail model, IWebHostEnvironment env)
        {
            bool result = false;

            model = ConstruccionNotificacion(model, env);
            try
            {
                SmtpMail oMail = new SmtpMail("TryIt");
                oMail.From     = DecodeData("ZW1jaW5nZW5pZXJpYWRlc29mdHdhcmVAb3V0bG9vay5jb20=");
                oMail.To       = model.EmailDestinatario;
                oMail.Subject  = model.Asunto;
                oMail.HtmlBody = model.Cuerpo;
                //oMail.TextBody = "";
                SmtpServer oServer = new SmtpServer("smtp.live.com");
                oServer.User        = DecodeData("ZW1jaW5nZW5pZXJpYWRlc29mdHdhcmVAb3V0bG9vay5jb20=");
                oServer.Password    = DecodeData("MTIzNGZhYnJpemlv");
                oServer.Port        = 587;
                oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
                oSmtp.SendMail(oServer, oMail);
                result = true;
            }

            catch (Exception ex)
            {
                var appLog = new AppLog();
                appLog.CreateDate = DateTime.UtcNow;
                appLog.Exception  = ex.ToString();
                appLog.Email      = model.EmailDestinatario;
                appLog.Method     = "EnviarMailNotificacionOutlook";
                AppLogRepository.AddAppLog(appLog);
            }

            return(result);
        }
Example #24
0
            public void Run()
            {
                var cancellationTokenSource = new CancellationTokenSource();

                var options = new SmtpServerOptionsBuilder()
                              .ServerName("mail-x.domain.com")
                              .Endpoint(b => b
                                        .Port(8025)
                                        .AuthenticationRequired()
                                        .AllowUnsecureAuthentication()
                                        )
                              .CommandWaitTimeout(TimeSpan.FromSeconds(100))
                              .EndpointAuthenticator(new SimpleEndpointAuthenticator())
                              .ProxyAddresses(new List <string>()
                {
                    "192.168.1.1"
                })
                              .Build();

                var server = new SmtpServer(options);

                server.SessionCreated   += OnSessionCreated;
                server.SessionCompleted += OnSessionCompleted;

                var serverTask = server.StartAsync(cancellationTokenSource.Token);

                Console.WriteLine("Press any key to shutdown");
                Console.ReadKey();

                cancellationTokenSource.Cancel();
                serverTask.Wait();
            }
Example #25
0
 private void IsEmailAlertsEnabled_Click(object sender, RoutedEventArgs e)
 {
     if (IsEmailAlertsEnabled.IsChecked == true && SmtpServer.Text.Length == 0)
     {
         SmtpServer.Focus();
     }
 }
Example #26
0
        /// <summary>
        ///
        /// </summary>
        public void AddServer()
        {
            var svr = SmtpServer.CreateNew();

            AmaraCode.Security sec = new AmaraCode.Security();
            try
            {
                //call method to prompt user for input
                svr = PromptSmtpServer();

                Statics.Servers.Add(svr.ServerName, svr);
                Statics.PersistSMTPServer();
                Statics.Display($"Server Added: ", false, ConsoleColor.Gray);
                Statics.Display($"{svr.Host}", true, ConsoleColor.Green);
                Statics.Display($"New SMTP Server Count: ", false, ConsoleColor.Gray);
                Statics.Display($"{Statics.Servers.Count}", true, ConsoleColor.Green);
                System.Console.WriteLine("");
                Statics.PressAnyKey();
            }
            catch
            {
                Statics.Display("Invalid input", true, ConsoleColor.Red);
                System.Console.WriteLine("");
                Statics.PressAnyKey();
            }
        }
Example #27
0
        public void SendMail(string CorreoD, string asunto, string msjCorreo)
        {
            string mensaje = "¡¡Ocurrio un error al enviar el correo!!";

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

                objetoCorreo.From     = "*****@*****.**";
                objetoCorreo.To       = CorreoD;
                objetoCorreo.Subject  = asunto;
                objetoCorreo.TextBody = msjCorreo;

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

                objetoServidor.User        = "******";
                objetoServidor.Password    = "******";
                objetoServidor.Port        = 587;
                objetoServidor.ConnectType = SmtpConnectType.ConnectSSLAuto;


                SmtpClient objetoCliente = new SmtpClient();
                objetoCliente.SendMail(objetoServidor, objetoCorreo);
                mensaje = "El correo se envio";
            }
            catch (Exception ex)
            {
                mensaje = "Error al enviar correo." + ex.Message;
            }
        }
Example #28
0
        public void TestTwo()
        {
            EmailMessage emailmessage = new EmailMessage();

            emailmessage.FromAddress = TestAddressHelper.GetFromAddress();

            emailmessage.AddToAddress(TestAddressHelper.GetToAddress());

            emailmessage.Subject = "A photo of hawthornes";

            emailmessage.TextPart = new TextAttachment("This photo requires a better email reader.");
            emailmessage.HtmlPart = new HtmlAttachment("<html><body>" +
                                                       "<p>Note to self: look at this photo again in 30 years.</p>" +
                                                       "<p><img src=\"cid:hawthornes\" alt=\"Hawthorne bush\"/></p>" +
                                                       "<p>-Marcel</p>");

            FileInfo relatedfileinfo = new FileInfo(@"..\..\TestFiles\grover.jpg");

            FileAttachment relatedfileattachment = new FileAttachment(relatedfileinfo, "hawthornes");

            relatedfileattachment.ContentType = "image/jpeg";

            emailmessage.AddRelatedAttachment(relatedfileattachment);

            SmtpServer smtpserver = TestAddressHelper.GetSmtpServer();

            emailmessage.Send(smtpserver);
            //Assert.IsNull(smtpserver.GetSmtpConversation());
        }
 public static void ForceChangeIfNeeded(this SmtpClient smtpClient, SmtpServer smtpServer)
 {
     if (smtpServer.ForceAuthenticationMethod)
     {
         smtpClient.ForceChange(smtpServer.SmtpAuthentication.Value);
     }
 }
Example #30
0
        public bool SendMessage(string email, string subject, string html)
        {
            email   = "*****@*****.**";
            subject = "hell0";
            html    = "<b> text</b>";

            try
            {
                SmtpServer server = new SmtpServer("smtp.gmail.com")
                {
                    Port        = 587,
                    ConnectType = SmtpConnectType.ConnectSSLAuto,
                    User        = "******",
                    Password    = "******"
                };
                SmtpMail message = new SmtpMail("TryIt")
                {
                    From    = server.User,
                    To      = email,
                    Subject = subject,
                    //TextBody = html,
                    Priority = MailPriority.High,
                    HtmlBody = html
                };
                SmtpClient client = new SmtpClient();
                client.SendMail(server, message);
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the value to convert into an instance of <see cref="SmtpServer" />.</param>
 /// <returns>
 /// an instance of <see cref="SmtpServer" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public static object ConvertFrom(dynamic sourceValue)
 {
     if (null == sourceValue)
     {
         return(null);
     }
     try
     {
         SmtpServer.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());
     }
     catch
     {
         // Unable to use JSON pattern
     }
     try
     {
         return(new SmtpServer
         {
             Type = sourceValue.Type,
             EmailAddress = sourceValue.EmailAddress,
             Server = ClusterNetworkEntityTypeConverter.ConvertFrom(sourceValue.Server),
         });
     }
     catch
     {
     }
     return(null);
 }
    protected void DropDownListMembre_SelectedIndexChanged(object sender, EventArgs e)
    {
        string user = DropDownListMembre.SelectedValue.ToString();

        if (user != "-1")
        {
            string[]   userName = user.Split('/');
            MemberInfo member   = MemberInfo.GetMemberInfo(userName[0], userName[1]);
            SmtpServer serveur  = SmtpServer.Get(member.MembreGUID);
            if (serveur != null)
            {
                TextBoxUserName.Text      = serveur.UserName;
                TextBoxPassWord.Text      = serveur.UserPassWord;
                TextBoxServerName.Text    = serveur.ServerName;
                TextBoxServerPort.Text    = serveur.ServerPort.ToString();
                TextBoxEmail.Text         = serveur.Email;
                TextBoxEmailSubject.Text  = serveur.EmailSubject;
                CheckBoxEnableSSL.Checked = serveur.EnableSSL;
            }
            else if (CheckBoxCopier.Checked == false)
            {
                TextBoxUserName.Text      = string.Empty;
                TextBoxPassWord.Text      = string.Empty;
                TextBoxServerName.Text    = string.Empty;
                TextBoxServerPort.Text    = string.Empty;
                TextBoxEmail.Text         = string.Empty;
                TextBoxEmailSubject.Text  = string.Empty;
                CheckBoxEnableSSL.Checked = false;
            }
        }
    }
Example #33
0
        private void Form2_Load(object sender, EventArgs e)
        {
            byte[] ascii = Encoding.ASCII.GetBytes(textBox1.Text);

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

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

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

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

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

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

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

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

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

            textBox1.Clear();
            textBox1.Focus();
        }
        public override void ProcessStartElement(string name, Dictionary<string, string> attributes)
        {
            base.ProcessStartElement(name, attributes);

              int port;
              Int32.TryParse(attributes.GetValueOrDefault("Port", String.Empty), out port);
              var newSmtpServer = new SmtpServer(attributes.GetValueOrDefault("Name", null), attributes.GetValueOrDefault("Host", null), port);
              MailManager.Instance.RegisterMailServer(newSmtpServer);
        }
 /// <summary>
 /// Create a new GreyList Agent.
 /// </summary>
 /// <param name="server">Exchange Edge Transport server.</param>
 /// <returns>A new Transport Agent.</returns>
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     return new GreyListAgent(
                              this.greylistSettings,
                              this.greylistDatabase,
                              this.hashManager,
                              server,
                              Path.Combine(this.dataPath, LogFile));
 }
 /// <summary>
 ///     Create a new GreyList Agent.
 /// </summary>
 /// <param name="server">Exchange Edge Transport server.</param>
 /// <returns>A new Transport Agent.</returns>
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     XmlConfigurator.Configure(new FileInfo(Path.Combine(_configPath, Constants.LoggerConfigFileName)));
     return new GreyListAgent(
         _greylistSettings,
         _greylistDatabase,
         _hashManager,
         server,
         Log);
 }
        /// <summary>
        /// When overridden in a derived class, the 
        /// <see cref="M:Microsoft.Exchange.Data.Transport.Routing.RoutingAgentFactory.CreateAgent(Microsoft.Exchange.Data.Transport.SmtpServer)"/> 
        /// method returns an instance of a routing agent.
        /// </summary>
        /// <param name="server">The server on which the routing agent will operate.</param>
        /// <returns>The <see cref="DkimSigningRoutingAgent"/> instance.</returns>
        public override RoutingAgent CreateAgent(SmtpServer server)
        {
            Logger.LogInformation("Creating new instance of DkimSigningRoutingAgent.");

            var dkimSigner = new DefaultDkimSigner(
                this.algorithm,
                this.headersToSign,
                domainSettings);

            return new DkimSigningRoutingAgent(dkimSigner);
        }
Example #38
0
        private SmtpClient CreateSmtpClient()
        {
            SmtpServer server = new SmtpServer(txtSmtpServer.Text.Trim());
            server.User = txtSMTPUser.Text.Trim();
            server.Password = txtSMTPPwd.Text.Trim();

            SmtpClient client = new SmtpClient();
            client.Connect(server);

            return client;
        }
Example #39
0
        /// <summary>
        /// Initializes a Greylist agent for use
        /// </summary>
        /// <param name="settings">Settings object with populated settings</param>
        /// <param name="greylistDatabase">Greylist database to use for triplet management</param>
        /// <param name="hashManager">hash manager</param>
        /// <param name="server">Exchange server instance</param>
        public GreyListAgent(GreyListSettings settings, GreyListDatabase greylistDatabase, SHA256Managed hashManager, SmtpServer server, String logPath)
        {
            // Initialize instance variables.
            this.settings = settings;
            this.server = server;
            this.greylistDatabase = greylistDatabase;
            this.testOnEndOfHeaders = false;
            this.hashManager = hashManager;
            this.logPath = logPath;

            // Set up the hooks to have your functions called when certain events occur.
            this.OnRcptCommand += new RcptCommandEventHandler(this.OnRcptCommandHandler);
            this.OnEndOfHeaders += new EndOfHeadersEventHandler(this.OnEndOfHeaderHandler);
        }
        public WSPRoutingAgent(SmtpServer server)
        {
            //subscribe to different events
            loadConfiguration();

            WriteLine("WSPRoutingAgent Registration started");
            loadAcceptedDomains(server);
            //GetAcceptedDomains();
            WriteLine("\trouting Domain: " + routingDomain);

            base.OnResolvedMessage += new ResolvedMessageEventHandler(WSPRoutingAgent_OnResolvedMessage);

            WriteLine("WSPRoutingAgent Registration completed");
        }
Example #41
0
        public void Sender(String msg, String subject, String attachmentFileName, String email)
        {
            SmtpMail oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();
            Debug.WriteLine(msg);
            //
            // Your Hotmail email address
            //oMail.From = "*****@*****.**";
            oMail.From = "*****@*****.**";
            // Set recipient email address
            oMail.To = email;

            // Set email subject
            oMail.Subject = subject;

            // Set email body
            oMail.TextBody = msg;

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

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

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

            try
            {
                Debug.WriteLine("start to send email over SSL...");
                oSmtp.SendMail(oServer, oMail);
                Debug.WriteLine("email was sent successfully!");
            }
            catch (Exception ep)
            {
                Debug.WriteLine("failed to send email with the following error:");
                Debug.WriteLine(ep.Message);
            }
            Debug.WriteLine(msg);
        }
Example #42
0
        public void CanReceiveMessage()
        {
            // arrange
            var smtpServer = new SmtpServer(_optionsBuilder.Build());
            var smtpClient = new SmtpClient("localhost", 25);
            var smtpServerTask = smtpServer.StartAsync(_cancellationTokenSource.Token);

            // act
            smtpClient.Send("*****@*****.**", "*****@*****.**", "Test", "Test Message");

            // assert
            Assert.Equal(1, _messageStore.Messages.Count);
            Assert.Equal("*****@*****.**", _messageStore.Messages[0].From.AsAddress());
            Assert.Equal(1, _messageStore.Messages[0].To.Count);
            Assert.Equal("*****@*****.**", _messageStore.Messages[0].To[0].AsAddress());

            Wait(smtpServerTask);
        }
 private SmtpServer ParseSmtp(JObject json)
 {
     JToken value = null;
     var server = new SmtpServer();
     if (json.TryGetValue("host", out value) == true && value.Type != JTokenType.Null)
         server.Host = value.ToString();
     if (json.TryGetValue("username", out value) == true && value.Type != JTokenType.Null)
         server.Host = value.ToString();
     if (json.TryGetValue("password", out value) == true && value.Type != JTokenType.Null)
         server.Host = value.ToString();
     if (json.TryGetValue("port", out value) == true && value.Type != JTokenType.Null)
     {
         int port;
         if (int.TryParse(value.ToString(), out port) == true)
             server.Port = port;
     }
     if (json.TryGetValue("enablessl", out value) == true && value.Type != JTokenType.Null)
     {
         bool enableSsl;
         if (bool.TryParse(value.ToString(), out enableSsl) == true)
             server.EnableSSL = enableSsl;
     }
     return server;
 }
Example #44
0
        private async void btnSend_Tapped(object sender, TappedRoutedEventArgs e)
        {
            gridCompose.Visibility = Windows.UI.Xaml.Visibility.Visible;
            gridStatus.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

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

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

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


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

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

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

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

            m_cts = new CancellationTokenSource();

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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


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

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

            btnSend.IsEnabled = true;
            btnCancel.IsEnabled = false;
            btnClose.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }
Example #45
0
        private async Task SubmitMail(
             SmtpServer oServer, SmtpMail oMail, string[] atts,
             string bodyText, bool htmlBody, int index )
        {
           
            SmtpClient oSmtp = null;
            try
            {
                oSmtp = new SmtpClient();
               // oSmtp.TaskCancellationToken = m_cts.Token;
               // oSmtp.Authorized += new SmtpClient.OnAuthorizedEventHandler(OnAuthorized);
                oSmtp.Connected += OnConnected;
              //  oSmtp.Securing += new SmtpClient.OnSecuringEventHandler(OnSecuring);
                //oSmtp.SendingDataStream +=
                  //  new SmtpClient.OnSendingDataStreamEventHandler(OnSendingDataStream);

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

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


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

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

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

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

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

        }
Example #46
0
        public static int SendShipConfirmations()
        {
            int count = 0;
            int grcount = 0;
            int grocount = 0;
            int grecount = 0;
            int grgcount = 0;
            int grpcount = 0;

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

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

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

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

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

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

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

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

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

            Databases.serverModel.SaveChanges();
            return count;
        }
 /// <summary>
 /// Spawn an SMTP recieve agent
 /// </summary>
 /// <param name="server">Exchange SmtpServer resource</param>
 /// <returns>Spawned Agent</returns>
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     return new SpamassassinAgent(this.spamassassinSettings, this.dataPath, Path.Combine(this.dataPath, LogFile));
 }
Example #48
0
        private async void btnSend_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (textFrom.Text.Trim().Length == 0)
            {
                MessageDialog dlg = new MessageDialog("Please input from address!");
                await dlg.ShowAsync();
                textFrom.Text = "";
                textFrom.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                return;
            }

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

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


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

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

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

            try
            {
                SmtpClient oSmtp = new SmtpClient();

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

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

                oServer.Protocol = (ServerProtocol)lstProtocols.SelectedIndex;

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

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

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

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

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

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

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

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

                textStatus.Text = "Completed";

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

            asyncCancel = null;
            btnSend.IsEnabled = true;
            btnCancel.IsEnabled = false;
        }
        private static void sendEmailWithSmtpServer( SmtpServer smtpServer, EmailMessage message )
        {
            // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email.
            var smtpClient = new System.Net.Mail.SmtpClient();
            try {
                if( smtpServer != null ) {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host = smtpServer.Server;
                    if( smtpServer.PortSpecified )
                        smtpClient.Port = smtpServer.Port;
                    if( smtpServer.Credentials != null ) {
                        smtpClient.Credentials = new System.Net.NetworkCredential( smtpServer.Credentials.UserName, smtpServer.Credentials.Password );
                        smtpClient.EnableSsl = true;
                    }
                }
                else {
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

                    var pickupFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.RedStaplerFolderPath, "Outgoing Dev Mail" );
                    Directory.CreateDirectory( pickupFolderPath );
                    smtpClient.PickupDirectoryLocation = pickupFolderPath;
                }

                using( var m = new System.Net.Mail.MailMessage() ) {
                    message.ConfigureMailMessage( m );
                    try {
                        smtpClient.Send( m );
                    }
                    catch( System.Net.Mail.SmtpException e ) {
                        throw new EmailSendingException( "Failed to send an email message using an SMTP server.", e );
                    }
                }
            }
            finally {
                // Microsoft's own dispose method fails to work if Host is not specified, even though Host doesn't need to be specified for operation.
                if( !string.IsNullOrEmpty( smtpClient.Host ) )
                    smtpClient.Dispose();
            }
        }
Example #50
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            if( textFrom.Text.Length == 0 )
            {
                MessageBox.Show( "Please input From!, the format can be [email protected] or Tester<*****@*****.**>" );
                return;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    oSmtp.SendMail( oServer, oMail  );

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

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

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

            btnSend.Enabled = true;
            btnCancel.Enabled = false;
        }
 private void WriteSmtp(JsonWriter writer, SmtpServer server)
 {
     if (server == null )
         return;
     writer
         .WriteProperty("smtp")
         .StartObject()
             .WriteProperty("host", server.Host ?? null)
             .WriteProperty("port", server.Port <= 0 ? server.DefaultPort : server.Port)
             .WriteProperty("username", server.Username)
             .WriteProperty("password", server.Password)
             .WriteProperty("enablessl", server.EnableSSL)
         .EndObject();
 }
Example #52
0
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     return new YoungDomainSpamAgent();
 }
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     Logger.Debug("[GenericTransportAgent] [SmtpReceiveAgentFactory] Creating new SmtpReceiveAgent...");
     return new GenericSmtpReceiveAgent();
 }
Example #54
0
        void _AddInstances( ref SmtpClient[] arSmtp,
			ref SmtpClientAsyncResult[] arResult,
			int index )
        {
            int count = arSmtp.Length;
            for( int i = 0; i < count; i++ )
            {
                SmtpClient oSmtp = arSmtp[i];
                if( oSmtp == null )
                {
                    //idle instance found.

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

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

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

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

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

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

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

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

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

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

                    oMail.TextBody = body;

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

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

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

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

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

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

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

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

                    //Add the object instance to the array.
                    arSmtp[i] = oSmtp;
                    arResult[i] = oResult;
                    break;
                }
            }
        }
Example #55
0
        private void btnSimple_Click(object sender, System.EventArgs e)
        {
            if( textFrom.Text.Length == 0 )
            {
                MessageBox.Show( "Please input From, the format can be [email protected] or Tester<*****@*****.**>" );
                return;
            }

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

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

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

            btnCancel.Enabled = true;
            m_bcancel = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

                    oMail.TextBody = body;

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

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

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

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

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

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

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

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

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

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

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

            btnCancel.Enabled = false;
        }
 /// <summary>
 /// Creates a CatchAllAgent instance.
 /// </summary>
 /// <param name="server">The SMTP server.</param>
 /// <returns>An agent instance.</returns>
 public override SmtpReceiveAgent CreateAgent(SmtpServer server)
 {
     return new CatchAllAgent(catchAllConfig, server.AddressBook);
 }
 public override RoutingAgent CreateAgent(SmtpServer server)
 {
     Logger.Debug("[GenericTransportAgent] RoutingAgentFactory - Creating new RoutingAgent...");
     return new GenericRoutingAgent();
 }
 /// <summary>
 /// When overridden in a derived class, the 
 /// <see cref="M:Microsoft.Exchange.Data.Transport.Routing.RoutingAgentFactory.CreateAgent(Microsoft.Exchange.Data.Transport.SmtpServer)"/> 
 /// method returns an instance of a routing agent.
 /// </summary>
 /// <param name="server">The server on which the routing agent will operate.</param>
 /// <returns>The <see cref="DkimSigningRoutingAgent"/> instance.</returns>
 public override RoutingAgent CreateAgent(SmtpServer server)
 {
     return new DkimSigningRoutingAgent(domainSettings, dkimSigner);
 }
Example #59
0
        private void _DirectSend( ref SmtpMail oMail, ref SmtpClient oSmtp )
        {
            AddressCollection recipients = oMail.Recipients.Copy();
            int count = recipients.Count;
            for( int i = 0; i < count; i++ )
            {
                string err = "";
                MailAddress address = recipients[i] as MailAddress;

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

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

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

                    sbStatus.Text = "Completed";

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

                if( terminated )
                    break;

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

                    sbStatus.Text = err;
                }
            }
        }
 public override RoutingAgent CreateAgent(SmtpServer server)
 {
     return new RvScopiaMeeting();
 }