Esempio n. 1
0
        public EmailerService(Logging.ILogger logger
			, Services.IConnectorService connectorService
			, Services.IAccountService accountService
			, Services.CryptoService cryptoService
			, Services.IScheduledTaskService taskService
			)
        {
            this.Logger = logger;
            this.ConnectorService = connectorService;
            this.CryptoService = cryptoService;
            this.AccountService = accountService;
            this.TaskService = taskService;

            var smtpSection = System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp") as System.Net.Configuration.SmtpSection;
            if (!smtpSection.From.IsNullOrTrimmedEmpty())
            {
                m_MailFrom = new MailAddress(smtpSection.From);
            }
            else
            {
                m_MailFrom = new MailAddress(ERPStoreApplication.WebSiteSettings.Contact.EmailSender,
                               ERPStoreApplication.WebSiteSettings.Contact.EmailSenderName);
            }

            var bccEmail = ERPStoreApplication.WebSiteSettings.Contact.BCCEmail ?? ERPStoreApplication.WebSiteSettings.Contact.ContactEmail;
            m_Bcc = new MailAddressCollection();
            if (bccEmail != null)
            {
                var emailList = bccEmail.Split(';');
                foreach (var email in emailList)
                {
                    m_Bcc.Add(email.Trim());
                }
            }
        }
Esempio n. 2
0
        public EMail(System.Net.Mail.MailAddress from,
                     System.Net.Mail.MailAddressCollection to,
                     System.Net.Mail.MailAddressCollection cc,
                     System.Net.Mail.MailAddressCollection bcc,
                     string subject,
                     string body)
        {
            Initialize();

            this.From = from;
            foreach (System.Net.Mail.MailAddress TO in to)
            {
                this.To.Add(TO);
            }
            foreach (System.Net.Mail.MailAddress CC in cc)
            {
                this.CC.Add(CC);
            }
            foreach (System.Net.Mail.MailAddress BCC in bcc)
            {
                this.Bcc.Add(BCC);
            }
            this.Subject = subject;
            this.Body    = body;
        }
Esempio n. 3
0
    public static void sendMailwithBCC(string bccEmail, string bccName, string toEmail, string toName, string fromEmail, string fromName, string subject, string body, bool isHtml)
    {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.From = new System.Net.Mail.MailAddress(fromEmail, fromName);
        System.Net.Mail.MailAddressCollection mc  = msg.To;
        System.Net.Mail.MailAddressCollection bcc = msg.Bcc;
        bcc.Add(new System.Net.Mail.MailAddress(bccEmail, bccName));
        mc.Add(new System.Net.Mail.MailAddress(toEmail, toName));

        msg.Body       = body;
        msg.Subject    = subject;
        msg.IsBodyHtml = isHtml;

        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["mailServer"]);
        if (ConfigurationManager.AppSettings["mailServer"].Contains("office.balancestudios.com"))
        {
            System.Net.NetworkCredential authenticationInfo = new System.Net.NetworkCredential("smtp", "b@l_SMTP");
            client.UseDefaultCredentials = false;
            client.Credentials           = authenticationInfo;
        }
        try
        {
            client.Send(msg);
        }
        catch (Exception e)
        {
        }
    }
Esempio n. 4
0
    private void EnviarMensajeUsuario(string EmailUsuario)
    {
        string validationCode = new Random().Next().ToString();

        //1.-Destino del mensaje
        System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
        MisDestinos.Add(new System.Net.Mail.MailAddress(EmailUsuario));

        //2.-Cuerpo del mensaje
        HttpServerUtility server   = HttpContext.Current.Server;
        string            sMensaje = "We have sucessfully received your registration request to DropKeys. To complete the subscription process, please click the following link :\r\n\r\n " + Request.Url.GetLeftPart(UriPartial.Authority) + "/validatecode.aspx?email=" +
                                     server.UrlEncode(EmailUsuario) + "&vc=" + validationCode + "\r\n\r\nThank you.";

        if (EmailUtils.SendMessageEmail(MisDestinos, "Verify your email", sMensaje))
        {
            using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
            {
                MembershipUser Usuario = Membership.GetUser(EmailUsuario, false);
                objUsuario.userid = Convert.ToInt32(Usuario.ProviderUserKey);
                if (objUsuario.bConsultar())
                {
                    objUsuario.mensaje_validacion = true;
                    objUsuario.validado           = false;
                    objUsuario.codigo_validacion  = validationCode;
                    objUsuario.bModificar();
                }
            }
        }
    }
Esempio n. 5
0
 private void AddAddressWithSemiColons(NetMail.MailAddressCollection collection, string addresses)
 {
     foreach (string address in addresses.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
     {
         if (!string.IsNullOrEmpty(address))
         {
             collection.Add(address.Trim());
         }
     }
 }
Esempio n. 6
0
        internal Nm.MailAddressCollection ToMailAddressCollection()
        {
            Nm.MailAddressCollection results = new Nm.MailAddressCollection();
            foreach (MailMessageRecipient recipient in this.InnerList)
            {
                results.Add(recipient.ToMailAddress());
            }

            // return...
            return(results);
        }
Esempio n. 7
0
        public static System.Net.Mail.MailAddressCollection ConvertTo(this MailAddressCollection addresses)
        {
            var rt = new System.Net.Mail.MailAddressCollection();

            if (addresses != null)
            {
                foreach (var address in addresses)
                {
                    rt.Add(address.ConvertTo());
                }
            }
            return(rt);
        }
Esempio n. 8
0
        public bool SendMail(string FromEmail, System.Net.Mail.MailAddressCollection ToEmails, string FromName, string Subject, string MailBody, string ReplyTo, Collection <Attachment> attachments)
        {
            System.Net.Mail.SmtpClient mSmtp = SmtpClient == null?GetSmtpClient("smtp.yandex.com.tr", 587, "*****@*****.**", "24ayarnurgul") : SmtpClient;

            System.Net.Mail.MailMessage mMessage = new System.Net.Mail.MailMessage();
            mMessage.HeadersEncoding = Encoding.Unicode;
            //mSmtp.UseDefaultCredentials = true;
            //MailBody = MailBody.Replace("#EbultenRemoveText", "");

            mMessage.From = new System.Net.Mail.MailAddress(FromEmail, FromName, Encoding.UTF8);
            foreach (System.Net.Mail.MailAddress item in ToEmails)
            {
                mMessage.To.Add(item);
            }
            if (ReplyTo != null)
            {
                mMessage.ReplyToList.Add(new System.Net.Mail.MailAddress(ReplyTo, FromName));
            }
            mMessage.BodyEncoding    = Encoding.UTF8;
            mMessage.Body            = MailBody;
            mMessage.Subject         = Subject;
            mMessage.SubjectEncoding = Encoding.UTF8;
            mMessage.HeadersEncoding = Encoding.UTF8;
            mMessage.IsBodyHtml      = true;
            IList mAttachs = mMessage.Attachments;

            if (attachments != null)
            {
                foreach (Attachment item in attachments)
                {
                    item.ContentStream.Position = 0;
                    item.NameEncoding           = Encoding.UTF8;
                    mAttachs.Add(item);
                }
            }
            try
            {
                mSmtp.Send(mMessage);
                return(true);
            }
            catch (Exception er)
            {
                //DBAdresDataContext dataContext = new DBAdresDataContext();
                //senderror mError = new senderror { email = null, error = getErrorMessages(er) };
                //dataContext.senderrors.InsertOnSubmit(mError);
                //dataContext.SubmitChanges();
                return(false);
            }
        }
Esempio n. 9
0
        private void CopyAddresses(Nm.MailAddressCollection addresses, MailMessageRecipientCollection recipients)
        {
            if (addresses == null)
            {
                throw new ArgumentNullException("addresses");
            }
            if (recipients == null)
            {
                throw new ArgumentNullException("recipients");
            }

            // copy...
            addresses.Clear();
            foreach (MailMessageRecipient recipient in recipients)
            {
                addresses.Add(recipient.ToMailAddress());
            }
        }
Esempio n. 10
0
        internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify,
                                     bool allowUnicode, out SmtpFailedRecipientException?exception)
        {
            ArgumentNullException.ThrowIfNull(sender);
            ArgumentNullException.ThrowIfNull(recipients);

            MailCommand.Send(_connection !, SmtpCommands.Mail, sender, allowUnicode);
            _failedRecipientExceptions.Clear();

            exception = null;
            string response;

            foreach (MailAddress address in recipients)
            {
                string smtpAddress = address.GetSmtpAddress(allowUnicode);
                string to          = smtpAddress + (_connection !.DSNEnabled ? deliveryNotify : string.Empty);
                if (!RecipientCommand.Send(_connection, to, out response))
                {
                    _failedRecipientExceptions.Add(
                        new SmtpFailedRecipientException(_connection.Reader !.StatusCode, smtpAddress, response));
                }
            }

            if (_failedRecipientExceptions.Count > 0)
            {
                if (_failedRecipientExceptions.Count == 1)
                {
                    exception = _failedRecipientExceptions[0];
                }
                else
                {
                    exception = new SmtpFailedRecipientsException(_failedRecipientExceptions, _failedRecipientExceptions.Count == recipients.Count);
                }

                if (_failedRecipientExceptions.Count == recipients.Count)
                {
                    exception.fatal = true;
                    throw exception;
                }
            }

            DataCommand.Send(_connection !);
            return(new MailWriter(_connection !.GetClosableStream(), encodeForTransport: true));
        }
Esempio n. 11
0
        public EMail(System.Net.Mail.MailAddress from,
                     System.Net.Mail.MailAddressCollection to,
                     System.Net.Mail.MailAddressCollection cc,
                     System.Net.Mail.MailAddressCollection bcc)
        {
            Initialize();

            foreach (System.Net.Mail.MailAddress TO in to)
            {
                this.To.Add(TO);
            }
            foreach (System.Net.Mail.MailAddress CC in cc)
            {
                this.CC.Add(CC);
            }
            foreach (System.Net.Mail.MailAddress BCC in bcc)
            {
                this.Bcc.Add(BCC);
            }
        }
Esempio n. 12
0
    private void EnviarMensajeAdministradores(string NuevoUsuario)
    {
        //1.-Destino del mensaje
        System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
        string[] usersInRole = Roles.GetUsersInRole("administrador");
        foreach (string userid in usersInRole)
        {
            MembershipUser user = Membership.GetUser((object)userid, false);
            if (user != null)
            {
                MisDestinos.Add(new System.Net.Mail.MailAddress(user.Email));
            }
        }

        //2.-Cuerpo del mensaje
        string sMensaje = "Le informo que el usuario " + NuevoUsuario + " ha solicitado su alta web en el portal de datos DropKeys. ";

        //3.-Envio del mensaje
        EmailUtils.SendMessageEmail(MisDestinos, "New user", sMensaje);
    }
Esempio n. 13
0
        internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
                                            string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
        {
            if (sender == null)
            {
                throw new ArgumentNullException(nameof(sender));
            }

            if (recipients == null)
            {
                throw new ArgumentNullException(nameof(recipients));
            }

            SendMailAsyncResult result = new SendMailAsyncResult(_connection, sender, recipients,
                                                                 allowUnicode, _connection.DSNEnabled ? deliveryNotify : null,
                                                                 callback, state);

            result.Send();
            return(result);
        }
Esempio n. 14
0
 internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify, out SmtpFailedRecipientException exception)
 {
     if (sender == null)
     {
         throw new ArgumentNullException("sender");
     }
     if (recipients == null)
     {
         throw new ArgumentNullException("recipients");
     }
     MailCommand.Send(this.connection, SmtpCommands.Mail, sender.SmtpAddress);
     this.failedRecipientExceptions.Clear();
     exception = null;
     foreach (MailAddress address in recipients)
     {
         string str;
         if (!RecipientCommand.Send(this.connection, this.connection.DSNEnabled ? (address.SmtpAddress + deliveryNotify) : address.SmtpAddress, out str))
         {
             this.failedRecipientExceptions.Add(new SmtpFailedRecipientException(this.connection.Reader.StatusCode, address.SmtpAddress, str));
         }
     }
     if (this.failedRecipientExceptions.Count > 0)
     {
         if (this.failedRecipientExceptions.Count == 1)
         {
             exception = (SmtpFailedRecipientException)this.failedRecipientExceptions[0];
         }
         else
         {
             exception = new SmtpFailedRecipientsException(this.failedRecipientExceptions, this.failedRecipientExceptions.Count == recipients.Count);
         }
         if (this.failedRecipientExceptions.Count == recipients.Count)
         {
             exception.fatal = true;
             throw exception;
         }
     }
     DataCommand.Send(this.connection);
     return(new MailWriter(this.connection.GetClosableStream()));
 }
        internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
                                            string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

            if (recipients == null)
            {
                throw new ArgumentNullException("recipients");
            }

            GlobalLog.Assert(recipients.Count > 0, "SmtpTransport::BeginSendMail()|recepients.Count <= 0");

            SendMailAsyncResult result = new SendMailAsyncResult(connection, sender, recipients,
                                                                 allowUnicode, connection.DSNEnabled ? deliveryNotify : null,
                                                                 callback, state);

            result.Send();
            return(result);
        }
Esempio n. 16
0
    protected void btnSendCode_Click(object sender, EventArgs e)
    {
        if (!usuarioid.HasValue)
        {
            return;
        }

        MembershipUser Usuario = Membership.GetUser(usuarioid, false);

        if (Usuario != null)
        {
            string validationCode = new Random().Next().ToString();

            //1.-Destino del mensaje
            System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
            MisDestinos.Add(new System.Net.Mail.MailAddress(Usuario.Email));

            //2.-Cuerpo del mensaje
            HttpServerUtility server   = HttpContext.Current.Server;
            string            sMensaje = "We have sucessfully received your registration request to DropKeys. To complete the subscription process, please click the following link :\r\n\r\n " + Request.Url.GetLeftPart(UriPartial.Authority) + "/validatecode.aspx?email=" +
                                         server.UrlEncode(Usuario.Email) + "&vc=" + validationCode + "\r\n\r\nThank you.";

            if (EmailUtils.SendMessageEmail(MisDestinos, "Verify your email", sMensaje))
            {
                using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
                {
                    objUsuario.userid = usuarioid;
                    if (objUsuario.bConsultar())
                    {
                        objUsuario.mensaje_validacion = true;
                        objUsuario.validado           = false;
                        objUsuario.codigo_validacion  = validationCode;
                        objUsuario.bModificar();
                    }
                }
            }
        }
    }
        internal Message(string from, string to) : this()
        {
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }
            if (from == string.Empty)
            {
                throw new ArgumentException(SR.GetString("net_emptystringcall", new object[] { "from" }), "from");
            }
            if (to == string.Empty)
            {
                throw new ArgumentException(SR.GetString("net_emptystringcall", new object[] { "to" }), "to");
            }
            this.from = new MailAddress(from);
            MailAddressCollection addresss = new MailAddressCollection();

            addresss.Add(to);
            this.to = addresss;
        }
        public void Send(MailMessage message)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.Web, this, "Send", message);
            }
            if (this.disposed)
            {
                throw new ObjectDisposedException(base.GetType().FullName);
            }
            try
            {
                if (Logging.On)
                {
                    Logging.PrintInfo(Logging.Web, this, "Send", "DeliveryMethod=" + this.DeliveryMethod.ToString());
                }
                if (Logging.On)
                {
                    Logging.Associate(Logging.Web, this, message);
                }
                SmtpFailedRecipientException exception = null;
                if (this.InCall)
                {
                    throw new InvalidOperationException(SR.GetString("net_inasync"));
                }
                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }
                if (this.DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    this.CheckHostAndPort();
                }
                MailAddressCollection recipients = new MailAddressCollection();
                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.GetString("SmtpFromRequired"));
                }
                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address2 in message.Bcc)
                    {
                        recipients.Add(address2);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address3 in message.CC)
                    {
                        recipients.Add(address3);
                    }
                }
                if (recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.GetString("SmtpRecipientRequired"));
                }
                this.transport.IdentityRequired = false;
                try
                {
                    this.InCall   = true;
                    this.timedOut = false;
                    this.timer    = new System.Threading.Timer(new TimerCallback(this.TimeOutCallback), null, this.Timeout, this.Timeout);
                    switch (this.DeliveryMethod)
                    {
                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                        if (this.EnableSsl)
                        {
                            throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl"));
                        }
                        break;

                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        if (this.EnableSsl)
                        {
                            throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl"));
                        }
                        goto Label_0235;

                    default:
                        goto Label_0244;
                    }
                    MailWriter fileMailWriter = this.GetFileMailWriter(this.PickupDirectoryLocation);
                    goto Label_0276;
Label_0235:
                    fileMailWriter = this.GetFileMailWriter(IisPickupDirectory.GetPickupDirectory());
                    goto Label_0276;
Label_0244:
                    this.GetConnection();
                    fileMailWriter = this.transport.SendMail((message.Sender != null) ? message.Sender : message.From, recipients, message.BuildDeliveryStatusNotificationString(), out exception);
Label_0276:
                    this.message = message;
                    message.Send(fileMailWriter, this.DeliveryMethod != SmtpDeliveryMethod.Network);
                    fileMailWriter.Close();
                    this.transport.ReleaseConnection();
                    if ((this.DeliveryMethod == SmtpDeliveryMethod.Network) && (exception != null))
                    {
                        throw exception;
                    }
                }
                catch (Exception exception2)
                {
                    if (Logging.On)
                    {
                        Logging.Exception(Logging.Web, this, "Send", exception2);
                    }
                    if ((exception2 is SmtpFailedRecipientException) && !((SmtpFailedRecipientException)exception2).fatal)
                    {
                        throw;
                    }
                    this.Abort();
                    if (this.timedOut)
                    {
                        throw new SmtpException(SR.GetString("net_timeout"));
                    }
                    if (((exception2 is SecurityException) || (exception2 is AuthenticationException)) || (exception2 is SmtpException))
                    {
                        throw;
                    }
                    throw new SmtpException(SR.GetString("SmtpSendMailFailure"), exception2);
                }
                finally
                {
                    this.InCall = false;
                    if (this.timer != null)
                    {
                        this.timer.Dispose();
                    }
                }
            }
            finally
            {
                if (Logging.On)
                {
                    Logging.Exit(Logging.Web, this, "Send", (string)null);
                }
            }
        }
Esempio n. 19
0
        public void Send(MailMessage message)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.Web, this, "Send", message);
            }
            if (disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            try {
                if (Logging.On)
                {
                    Logging.PrintInfo(Logging.Web, this, "Send", "DeliveryMethod=" + DeliveryMethod.ToString());
                }
                if (Logging.On)
                {
                    Logging.Associate(Logging.Web, this, message);
                }
                SmtpFailedRecipientException recipientException = null;

                if (InCall)
                {
                    throw new InvalidOperationException(SR.GetString(SR.net_inasync));
                }

                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    CheckHostAndPort();
                }

                MailAddressCollection recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.SmtpFromRequired));
                }

                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address in message.Bcc)
                    {
                        recipients.Add(address);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address in message.CC)
                    {
                        recipients.Add(address);
                    }
                }

                if (recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.GetString(SR.SmtpRecipientRequired));
                }

                transport.IdentityRequired = false;  // everything completes on the same thread.

                try {
                    InCall   = true;
                    timedOut = false;
                    timer    = new Timer(new TimerCallback(this.TimeOutCallback), null, Timeout, Timeout);
                    bool   allowUnicode    = false;
                    string pickupDirectory = PickupDirectoryLocation;

                    MailWriter writer;
                    switch (DeliveryMethod)
                    {
#if !FEATURE_PAL
                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        pickupDirectory = IisPickupDirectory.GetPickupDirectory();
                        goto case SmtpDeliveryMethod.SpecifiedPickupDirectory;
#endif // !FEATURE_PAL
                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                        if (EnableSsl)
                        {
                            throw new SmtpException(SR.GetString(SR.SmtpPickupDirectoryDoesnotSupportSsl));
                        }
                        allowUnicode = IsUnicodeSupported();     // Determend by the DeliveryFormat paramiter
                        ValidateUnicodeRequirement(message, recipients, allowUnicode);
                        writer = GetFileMailWriter(pickupDirectory);
                        break;

                    case SmtpDeliveryMethod.Network:
                    default:
                        GetConnection();
                        // Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
                        allowUnicode = IsUnicodeSupported();
                        ValidateUnicodeRequirement(message, recipients, allowUnicode);
                        writer = transport.SendMail(message.Sender ?? message.From, recipients,
                                                    message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
                        break;
                    }
                    this.message = message;
                    message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
                    writer.Close();
                    transport.ReleaseConnection();

                    //throw if we couldn't send to any of the recipients
                    if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
                    {
                        throw recipientException;
                    }
                }
                catch (Exception e) {
                    if (Logging.On)
                    {
                        Logging.Exception(Logging.Web, this, "Send", e);
                    }


                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                    {
                        throw;
                    }


                    Abort();
                    if (timedOut)
                    {
                        throw new SmtpException(SR.GetString(SR.net_timeout));
                    }

                    if (e is SecurityException ||
                        e is AuthenticationException ||
                        e is SmtpException)
                    {
                        throw;
                    }

                    throw new SmtpException(SR.GetString(SR.SmtpSendMailFailure), e);
                }
                finally {
                    InCall = false;
                    if (timer != null)
                    {
                        timer.Dispose();
                    }
                }
            } finally {
                if (Logging.On)
                {
                    Logging.Exit(Logging.Web, this, "Send", null);
                }
            }
        }
Esempio n. 20
0
        public void Send(MailMessage message)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
                NetEventSource.Associate(this, message);
            }

            SmtpFailedRecipientException?recipientException = null;

            if (InCall)
            {
                throw new InvalidOperationException(SR.net_inasync);
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (DeliveryMethod == SmtpDeliveryMethod.Network)
            {
                CheckHostAndPort();
            }

            MailAddressCollection recipients = new MailAddressCollection();

            if (message.From == null)
            {
                throw new InvalidOperationException(SR.SmtpFromRequired);
            }

            if (message.To != null)
            {
                foreach (MailAddress address in message.To)
                {
                    recipients.Add(address);
                }
            }
            if (message.Bcc != null)
            {
                foreach (MailAddress address in message.Bcc)
                {
                    recipients.Add(address);
                }
            }
            if (message.CC != null)
            {
                foreach (MailAddress address in message.CC)
                {
                    recipients.Add(address);
                }
            }

            if (recipients.Count == 0)
            {
                throw new InvalidOperationException(SR.SmtpRecipientRequired);
            }

            _transport.IdentityRequired = false;  // everything completes on the same thread.

            try
            {
                InCall    = true;
                _timedOut = false;
                _timer    = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
                bool   allowUnicode    = false;
                string?pickupDirectory = PickupDirectoryLocation;

                MailWriter writer;
                switch (DeliveryMethod)
                {
                case SmtpDeliveryMethod.PickupDirectoryFromIis:
                    throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                    if (EnableSsl)
                    {
                        throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
                    }

                    allowUnicode = IsUnicodeSupported();     // Determined by the DeliveryFormat parameter
                    ValidateUnicodeRequirement(message, recipients, allowUnicode);
                    writer = GetFileMailWriter(pickupDirectory);
                    break;

                case SmtpDeliveryMethod.Network:
                default:
                    GetConnection();
                    // Detected during GetConnection(), restrictable using the DeliveryFormat parameter
                    allowUnicode = IsUnicodeSupported();
                    ValidateUnicodeRequirement(message, recipients, allowUnicode);
                    writer = _transport.SendMail(message.Sender ?? message.From, recipients,
                                                 message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
                    break;
                }
                _message = message;
                message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
                writer.Close();

                //throw if we couldn't send to any of the recipients
                if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
                {
                    throw recipientException;
                }
            }
            catch (Exception e)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(this, e);
                }

                if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                {
                    throw;
                }

                Abort();
                if (_timedOut)
                {
                    throw new SmtpException(SR.net_timeout);
                }

                if (e is SecurityException ||
                    e is AuthenticationException ||
                    e is SmtpException)
                {
                    throw;
                }

                throw new SmtpException(SR.SmtpSendMailFailure, e);
            }
            finally
            {
                InCall = false;
                if (_timer != null)
                {
                    _timer.Dispose();
                }
            }
        }
Esempio n. 21
0
        public void SendAsync(MailMessage message, object userToken)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, message, userToken, _transport);
            }

            try
            {
                if (InCall)
                {
                    throw new InvalidOperationException(SR.net_inasync);
                }

                if (message == null)
                {
                    throw new ArgumentNullException(nameof(message));
                }

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    CheckHostAndPort();
                }

                _recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.SmtpFromRequired);
                }

                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        _recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address in message.Bcc)
                    {
                        _recipients.Add(address);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address in message.CC)
                    {
                        _recipients.Add(address);
                    }
                }

                if (_recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.SmtpRecipientRequired);
                }

                try
                {
                    InCall     = true;
                    _cancelled = false;
                    _message   = message;
                    string pickupDirectory = PickupDirectoryLocation;

                    CredentialCache cache;
                    // Skip token capturing if no credentials are used or they don't include a default one.
                    // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
                    _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));

                    _asyncOp = AsyncOperationManager.CreateOperation(userToken);
                    switch (DeliveryMethod)
                    {
                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                    {
                        if (EnableSsl)
                        {
                            throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
                        }

                        _writer = GetFileMailWriter(pickupDirectory);
                        bool allowUnicode = IsUnicodeSupported();
                        ValidateUnicodeRequirement(message, _recipients, allowUnicode);
                        message.Send(_writer, true, allowUnicode);

                        if (_writer != null)
                        {
                            _writer.Close();
                        }

                        _transport.ReleaseConnection();
                        AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
                        InCall = false;
                        _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
                        break;
                    }

                    case SmtpDeliveryMethod.Network:
                    default:
                        _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
                        lock (_operationCompletedResult.StartPostingAsyncOp())
                        {
                            if (NetEventSource.IsEnabled)
                            {
                                NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
                            }
                            _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
                            _operationCompletedResult.FinishPostingAsyncOp();
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    InCall = false;

                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(this, e);
                    }

                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                    {
                        throw;
                    }

                    Abort();
                    if (_timedOut)
                    {
                        throw new SmtpException(SR.net_timeout);
                    }

                    if (e is SecurityException ||
                        e is AuthenticationException ||
                        e is SmtpException)
                    {
                        throw;
                    }

                    throw new SmtpException(SR.SmtpSendMailFailure, e);
                }
            }
            finally
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this);
                }
            }
        }
Esempio n. 22
0
        public void SendAsync(MailMessage message, object userToken)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (Logging.On)
            {
                Logging.Enter(Logging.Web, this, "SendAsync", "DeliveryMethod=" + DeliveryMethod.ToString());
            }
            GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync Transport#" + ValidationHelper.HashString(transport));
            try {
                if (InCall)
                {
                    throw new InvalidOperationException(SR.GetString(SR.net_inasync));
                }

                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    CheckHostAndPort();
                }

                recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.SmtpFromRequired));
                }

                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address in message.Bcc)
                    {
                        recipients.Add(address);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address in message.CC)
                    {
                        recipients.Add(address);
                    }
                }

                if (recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.GetString(SR.SmtpRecipientRequired));
                }

                try {
                    InCall       = true;
                    cancelled    = false;
                    this.message = message;
                    string pickupDirectory = PickupDirectoryLocation;

#if !FEATURE_PAL
                    CredentialCache cache;
                    // Skip token capturing if no credentials are used or they don't include a default one.
                    // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
                    transport.IdentityRequired = Credentials != null && (Credentials is SystemNetworkCredential || (cache = Credentials as CredentialCache) == null || cache.IsDefaultInCache);
#endif // !FEATURE_PAL

                    asyncOp = AsyncOperationManager.CreateOperation(userToken);
                    switch (DeliveryMethod)
                    {
#if !FEATURE_PAL
                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        pickupDirectory = IisPickupDirectory.GetPickupDirectory();
                        goto case SmtpDeliveryMethod.SpecifiedPickupDirectory;
#endif // !FEATURE_PAL
                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                    {
                        if (EnableSsl)
                        {
                            throw new SmtpException(SR.GetString(SR.SmtpPickupDirectoryDoesnotSupportSsl));
                        }
                        writer = GetFileMailWriter(pickupDirectory);
                        bool allowUnicode = IsUnicodeSupported();
                        ValidateUnicodeRequirement(message, recipients, allowUnicode);
                        message.Send(writer, true, allowUnicode);

                        if (writer != null)
                        {
                            writer.Close();
                        }

                        transport.ReleaseConnection();
                        AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, asyncOp.UserSuppliedState);
                        InCall = false;
                        asyncOp.PostOperationCompleted(onSendCompletedDelegate, eventArgs);
                        break;
                    }

                    case SmtpDeliveryMethod.Network:
                    default:
                        operationCompletedResult = new ContextAwareResult(transport.IdentityRequired, true, null, this, _ContextSafeCompleteCallback);
                        lock (operationCompletedResult.StartPostingAsyncOp())
                        {
                            GlobalLog.Print("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync calling BeginConnect.  Transport#" + ValidationHelper.HashString(transport));
                            transport.BeginGetConnection(ServicePoint, operationCompletedResult, ConnectCallback, operationCompletedResult);
                            operationCompletedResult.FinishPostingAsyncOp();
                        }
                        break;
                    }
                }
                catch (Exception e) {
                    InCall = false;

                    if (Logging.On)
                    {
                        Logging.Exception(Logging.Web, this, "Send", e);
                    }

                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                    {
                        throw;
                    }

                    Abort();
                    if (timedOut)
                    {
                        throw new SmtpException(SR.GetString(SR.net_timeout));
                    }

                    if (e is SecurityException ||
                        e is AuthenticationException ||
                        e is SmtpException)
                    {
                        throw;
                    }

                    throw new SmtpException(SR.GetString(SR.SmtpSendMailFailure), e);
                }
            } finally {
                if (Logging.On)
                {
                    Logging.Exit(Logging.Web, this, "SendAsync", null);
                }
                GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync");
            }
        }
Esempio n. 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string email = string.Empty;
            string vc    = string.Empty;

            if (!string.IsNullOrEmpty(Request.QueryString["email"]))
            {
                email = Request.QueryString["email"].ToString();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["vc"]))
            {
                vc = Request.QueryString["vc"].ToString();
            }

            // Validate this email and validation code
            if (string.IsNullOrEmpty(email))
            {
                lbResultado.Text     = "<div class='alert alert-danger fade in'>Sorry but the e-mail user " + email + " can't be found in our database</div>";
                btnGoWebsite.Visible = false;
            }
            else if (string.IsNullOrEmpty(vc))
            {
                // Send email for validation
                MembershipUser Usuario = Membership.GetUser(email, false);
                using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
                {
                    objUsuario.userid   = Convert.ToInt32(Usuario.ProviderUserKey);
                    objUsuario.validado = true;
                    if (objUsuario.bConsultar())
                    {
                        //GREEN
                        lbResultado.Text = "<div class='alert alert-success fade in'>The e-mail user " + email + " has already been successfully validated, it is not necessary re-validate it again.</div>";
                    }
                    else
                    {
                        try
                        {
                            string validationCode = new Random().Next().ToString();

                            //1.-Destino del mensaje
                            System.Net.Mail.MailAddressCollection MisDestinos = new System.Net.Mail.MailAddressCollection();
                            MisDestinos.Add(new System.Net.Mail.MailAddress(email));

                            //2.-Cuerpo del mensaje
                            HttpServerUtility server   = HttpContext.Current.Server;
                            string            sMensaje = "We have received your registration request to DropKeys. To complete the subscription process, please click the following link:\r\n\r\n " + Request.Url.GetLeftPart(UriPartial.Authority) + "/validatecode.aspx?email=" +
                                                         server.UrlEncode(email) + "&vc=" + validationCode +
                                                         "\r\n\r\nThank you.";

                            if (EmailUtils.SendMessageEmail(MisDestinos, "Check your email", sMensaje))
                            {
                                objUsuario.userid             = Convert.ToInt32(Usuario.ProviderUserKey);
                                objUsuario.mensaje_validacion = true;
                                objUsuario.validado           = false;
                                objUsuario.codigo_validacion  = validationCode;
                                objUsuario.suscrito           = false;
                                objUsuario.bModificar();

                                lbResultado.Text = "<div class='alert alert-success fade in'>We have sent an e-mail to " + email + ". Please click on the link enclosed in the mail to complete the subscription process.</div>";
                            }
                            else
                            {
                                //RED
                                lbResultado.Text = "<div class='alert alert-danger fade in'>We are very sorry we were unable to send the email with the validation key <a href=\"validatecode.aspx?email=" + Server.UrlEncode(email) + "\">Press here</a> to try it again.</div>";
                            }
                        }
                        catch (Exception)
                        {
                            //RED
                            lbResultado.Text = "<div class='alert alert-danger fade in'>We are very sorry we were unable to send the email with the validation key <a href=\"validatecode.aspx?email=" + Server.UrlEncode(email) + "\">Press here</a> to try it again.</div>";
                        }
                    }
                }
            }
            else if (!string.IsNullOrEmpty(vc))
            {
                MembershipUser Usuario = Membership.GetUser(email, false);
                using (Clases.cASPNET_INFO_USUARIO objUsuario = new Clases.cASPNET_INFO_USUARIO())
                {
                    objUsuario.userid            = Convert.ToInt32(Usuario.ProviderUserKey);
                    objUsuario.codigo_validacion = vc;
                    if (objUsuario.bConsultar())
                    {
                        //GREEN
                        lbResultado.Text    = "<div class='alert alert-success fade in'>Congratulations, the e-mail " + email + " has been successfully validated.</div>";
                        objUsuario.validado = true;
                        objUsuario.suscrito = true;
                        objUsuario.bModificar();

                        //Logeamos
                        FormsAuthentication.SetAuthCookie(email, true);
                    }
                    else
                    {
                        //RED
                        lbResultado.Text = "<div class='alert alert-danger fade in'>Sorry but the email " + email + " could not be validated by our system. The validation code provided is not correct. " +
                                           "<a href=\"validatecode.aspx?email=" + email + "\">Click here</a>" + " to request a new validation code.</div>";
                    }
                }
            }
        }
    }
Esempio n. 24
0
 public bool SendMail(string FromEmail, System.Net.Mail.MailAddressCollection toEmails, string adSoyad, string Subject, string MailBody, string ReplyTo)
 {
     return(SendMail(FromEmail, toEmails, adSoyad, Subject, MailBody, ReplyTo, null));
 }
        public void SendAsync(MailMessage message, object userToken)
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException(base.GetType().FullName);
            }
            if (Logging.On)
            {
                Logging.Enter(Logging.Web, this, "SendAsync", "DeliveryMethod=" + this.DeliveryMethod.ToString());
            }
            try
            {
                if (this.InCall)
                {
                    throw new InvalidOperationException(SR.GetString("net_inasync"));
                }
                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }
                if (this.DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    this.CheckHostAndPort();
                }
                this.recipients = new MailAddressCollection();
                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.GetString("SmtpFromRequired"));
                }
                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        this.recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address2 in message.Bcc)
                    {
                        this.recipients.Add(address2);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address3 in message.CC)
                    {
                        this.recipients.Add(address3);
                    }
                }
                if (this.recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.GetString("SmtpRecipientRequired"));
                }
                try
                {
                    CredentialCache cache;
                    this.InCall    = true;
                    this.cancelled = false;
                    this.message   = message;
                    this.transport.IdentityRequired = ((this.Credentials != null) && ComNetOS.IsWinNt) && (((this.Credentials is SystemNetworkCredential) || ((cache = this.Credentials as CredentialCache) == null)) || cache.IsDefaultInCache);
                    this.asyncOp = AsyncOperationManager.CreateOperation(userToken);
                    switch (this.DeliveryMethod)
                    {
                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                        if (this.EnableSsl)
                        {
                            throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl"));
                        }
                        break;

                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        if (this.EnableSsl)
                        {
                            throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl"));
                        }
                        goto Label_02B2;

                    default:
                        goto Label_0329;
                    }
                    this.writer = this.GetFileMailWriter(this.PickupDirectoryLocation);
                    message.Send(this.writer, this.DeliveryMethod != SmtpDeliveryMethod.Network);
                    if (this.writer != null)
                    {
                        this.writer.Close();
                    }
                    this.transport.ReleaseConnection();
                    AsyncCompletedEventArgs arg = new AsyncCompletedEventArgs(null, false, this.asyncOp.UserSuppliedState);
                    this.InCall = false;
                    this.asyncOp.PostOperationCompleted(this.onSendCompletedDelegate, arg);
                    return;

Label_02B2:
                    this.writer = this.GetFileMailWriter(IisPickupDirectory.GetPickupDirectory());
                    message.Send(this.writer, this.DeliveryMethod != SmtpDeliveryMethod.Network);
                    if (this.writer != null)
                    {
                        this.writer.Close();
                    }
                    this.transport.ReleaseConnection();
                    AsyncCompletedEventArgs args2 = new AsyncCompletedEventArgs(null, false, this.asyncOp.UserSuppliedState);
                    this.InCall = false;
                    this.asyncOp.PostOperationCompleted(this.onSendCompletedDelegate, args2);
                    return;

Label_0329:
                    this.operationCompletedResult = new ContextAwareResult(this.transport.IdentityRequired, true, null, this, _ContextSafeCompleteCallback);
                    lock (this.operationCompletedResult.StartPostingAsyncOp())
                    {
                        this.transport.BeginGetConnection(this.ServicePoint, this.operationCompletedResult, new AsyncCallback(this.ConnectCallback), this.operationCompletedResult);
                        this.operationCompletedResult.FinishPostingAsyncOp();
                    }
                }
                catch (Exception exception)
                {
                    this.InCall = false;
                    if (Logging.On)
                    {
                        Logging.Exception(Logging.Web, this, "Send", exception);
                    }
                    if ((exception is SmtpFailedRecipientException) && !((SmtpFailedRecipientException)exception).fatal)
                    {
                        throw;
                    }
                    this.Abort();
                    if (this.timedOut)
                    {
                        throw new SmtpException(SR.GetString("net_timeout"));
                    }
                    if (((exception is SecurityException) || (exception is AuthenticationException)) || (exception is SmtpException))
                    {
                        throw;
                    }
                    throw new SmtpException(SR.GetString("SmtpSendMailFailure"), exception);
                }
            }
            finally
            {
                if (Logging.On)
                {
                    Logging.Exit(Logging.Web, this, "SendAsync", (string)null);
                }
            }
        }