Exemple #1
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();
                }
            }
        }
    }
Exemple #2
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)
        {
        }
    }
        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());
                }
            }
        }
Exemple #4
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());
         }
     }
 }
Exemple #5
0
        internal Nm.MailAddressCollection ToMailAddressCollection()
        {
            Nm.MailAddressCollection results = new Nm.MailAddressCollection();
            foreach (MailMessageRecipient recipient in this.InnerList)
            {
                results.Add(recipient.ToMailAddress());
            }

            // return...
            return(results);
        }
Exemple #6
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);
        }
Exemple #7
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());
            }
        }
Exemple #8
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);
    }
Exemple #9
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;
        }
Exemple #11
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();
                }
            }
        }
Exemple #12
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);
                }
            }
        }
Exemple #13
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>";
                    }
                }
            }
        }
    }
Exemple #14
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");
            }
        }
Exemple #15
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);
                }
            }
        }
        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);
                }
            }
        }