示例#1
0
    protected override void OnPreRender(EventArgs e)
    {
        SmtpDeliveryMethod method = SmtpDeliveryMethod.Network;

        if (!string.IsNullOrEmpty(inputDelivery.SelectedValue))
        {
            method = (SmtpDeliveryMethod)Enum.Parse(typeof(SmtpDeliveryMethod), inputDelivery.SelectedValue);
        }

        switch (method)
        {
        case SmtpDeliveryMethod.Network:
            panelServerPort.Visible              = true;
            panelUsernamePassword.Visible        = true;
            panelPickupDirectoryLocation.Visible = false;
            break;

        case SmtpDeliveryMethod.PickupDirectoryFromIis:
            panelServerPort.Visible              = false;
            panelUsernamePassword.Visible        = false;
            panelPickupDirectoryLocation.Visible = false;
            break;

        case SmtpDeliveryMethod.SpecifiedPickupDirectory:
            panelServerPort.Visible              = false;
            panelUsernamePassword.Visible        = false;
            panelPickupDirectoryLocation.Visible = true;
            break;
        }

        base.OnPreRender(e);
    }
示例#2
0
        private void Initialize()
        {
            // Load configuration
            SmtpUsername       = LogHelper.ParseString("SmtpUsername", "");
            SmtpPassword       = LogHelper.ParseString("SmtpPassword", "");
            SmtpDomain         = LogHelper.ParseString("SmtpDomain", "");
            SmtpServer         = LogHelper.ParseString("SmtpServer", "");
            SmtpPickupFolder   = LogHelper.ParseString("SmtpPickupFolder", "");
            SmtpEnableSsl      = LogHelper.ParseBool("SmtpEnableSsl", false);
            SmtpFrom           = LogHelper.ParseString("SmtpFrom", "");
            SmtpSendCopyTo     = LogHelper.ParseString("SmtpSendCopyTo", "");
            ErrorRecipients    = LogHelper.ParseString("ErrorRecipients", "");
            ErrorNotifications = LogHelper.ParseBool("ErrorNotifications", true);
            ErrorCodeSuspended = LogHelper.ParseString("ErrorCodeSuspended", "");
            SmtpDeliveryMethod = LogHelper.ParseEnum("ErrorDeliveryMethod", SmtpDeliveryMethod.Network);
            // Maximum 10 errors of same type per 5 minutes (2880 per day).
            ErrorLimitMax = LogHelper.ParseInt("ErrorLimitMax", 5);
            ErrorLimitAge = LogHelper.ParseSpan("ErrorLimitAge", new TimeSpan(0, 5, 0));
            // FQDN Fix
            IPGlobalProperties ip = IPGlobalProperties.GetIPGlobalProperties();

            if (!string.IsNullOrEmpty(ip.HostName) && !string.IsNullOrEmpty(ip.DomainName))
            {
                LocalHostName = ip.HostName + "." + ip.DomainName;
            }
        }
示例#3
0
        private void BindUserServices()
        {
            Bind <IMailService>().ToMethod(ctx =>
            {
                var appSettingsReader = new AppSettingsReader();

                string ourEmail           = (string)appSettingsReader.GetValue("OurMailAddress", typeof(string));
                string host               = (string)appSettingsReader.GetValue("Host", typeof(string));
                int port                  = (int)appSettingsReader.GetValue("Port", typeof(int));
                SmtpDeliveryMethod method = (SmtpDeliveryMethod)appSettingsReader.GetValue("SMTPDeliveryMethod", typeof(int));
                string ourMailPassword    = (string)appSettingsReader.GetValue("OurMailPassword", typeof(string));
                bool enableSsl            = (bool)appSettingsReader.GetValue("EnableSSL", typeof(bool));

                var client = new SmtpClient(host, port)
                {
                    DeliveryMethod = method,
                    Credentials    = new NetworkCredential(ourEmail, ourMailPassword),
                    EnableSsl      = enableSsl
                };

                return(new MailService(client, ourEmail));
            });

            Bind <IUserService>().To <UserService>();
            Bind <IUserRoleService>().To <UserRoleService>();
        }
示例#4
0
 public MailModel(
     string userName,
     string password,
     string host,
     string mailAddress,
     IList <string> toAddress,
     bool enableSsl,
     SmtpDeliveryMethod deliveryMethod,
     int port,
     string title,
     string content,
     IList <string> mailFiles,
     IList <string> ccAddress,
     IList <string> bccAddress,
     MailPriority eMailPriority
     )
 {
     UserName        = userName;
     Password        = password;
     Host            = host;
     FromMailAddress = mailAddress;
     ToAddress       = toAddress;
     EnableSsl       = enableSsl;
     DeliveryMethod  = deliveryMethod;
     Port            = port;
     Subject         = title;
     Body            = content;
     MailFiles       = mailFiles;
     CcAddress       = ccAddress;
     BccAddress      = bccAddress;
     EMailPriority   = eMailPriority;
 }
示例#5
0
        private void Initialize()
        {
            // Load configuration
            SmtpUsername       = LogHelper.ParseString("SmtpUsername", "");
            SmtpPassword       = LogHelper.ParseString("SmtpPassword", "");
            SmtpDomain         = LogHelper.ParseString("SmtpDomain", "");
            SmtpServer         = LogHelper.ParseString("SmtpServer", "");
            SmtpPickupFolder   = LogHelper.ParseString("SmtpPickupFolder", "");
            SmtpEnableSsl      = LogHelper.ParseBool("SmtpEnableSsl", false);
            SmtpFrom           = LogHelper.ParseString("SmtpFrom", "");
            SmtpSendCopyTo     = LogHelper.ParseString("SmtpSendCopyTo", "");
            SmtpDeliveryMethod = LogHelper.ParseEnum("ErrorDeliveryMethod", SmtpDeliveryMethod.Network);
            // Error reporting.
            ErrorRecipients = LogHelper.ParseString("ErrorRecipients", "");
            var errorNotifications = !string.IsNullOrEmpty(ErrorRecipients);

            ErrorNotifications = LogHelper.ParseBool("ErrorNotifications", errorNotifications);
            ErrorCodeSuspended = LogHelper.ParseString("ErrorCodeSuspended", "");
            // FQDN Fix
            IPGlobalProperties ip = IPGlobalProperties.GetIPGlobalProperties();

            if (!string.IsNullOrEmpty(ip.HostName) && !string.IsNullOrEmpty(ip.DomainName))
            {
                LocalHostName = ip.HostName + "." + ip.DomainName;
            }
        }
示例#6
0
        private void SendMail(string smtpServer, string @from, string password, string mailto, string caption, string message, int port, bool enableSsl,
                              SmtpDeliveryMethod smtpDeliveryMethod, bool isBodyHtml,
                              IEnumerable <Attachment> attachments)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from);
                mail.To.Add(new MailAddress(mailto));
                mail.Subject    = caption;
                mail.Body       = message;
                mail.IsBodyHtml = isBodyHtml;

                foreach (var attachment in attachments)
                {
                    mail.Attachments.Add(attachment);
                }

                SmtpClient client = new SmtpClient
                {
                    Host           = smtpServer,
                    Port           = port,
                    EnableSsl      = enableSsl,
                    Credentials    = new NetworkCredential(@from.Split('@')[0], password),
                    DeliveryMethod = smtpDeliveryMethod
                };
                client.Send(mail);
                mail.Dispose();
            }
            catch (Exception e)
            {
                //throw new Exception("Mail.Send: " + e.Message);
            }
        }
示例#7
0
 internal SmtpSectionInternal(SmtpSection section)
 {
     this.deliveryMethod           = section.DeliveryMethod;
     this.from                     = section.From;
     this.network                  = new SmtpNetworkElementInternal(section.Network);
     this.specifiedPickupDirectory = new SmtpSpecifiedPickupDirectoryElementInternal(section.SpecifiedPickupDirectory);
 }
        public void Execute(IJobExecutionContext context)
        {
            SmtpConfiguration smtpconfig = this._SmtpConfigurationRepository.FindDefault();

            SmtpDeliveryMethod   method   = this.GetStmpDeliveryMethod(smtpconfig);
            SecurityProtocolType protocol = this.GetSecurityProtocolType(smtpconfig);

            foreach (Administrator admin in this._AdministratorRepository.FindAll())
            {
                long executing = 0;
                long completed = 0;
                long failed    = 0;

                foreach (Client client in this._ClientRepository.FindByAdmin(admin.ID))
                {
                    executing += this._BackupRepository.GetCount(client.ID, 0);
                    completed += this._BackupRepository.GetCount(client.ID, 1);
                    failed    += this._BackupRepository.GetCount(client.ID, 2);
                }

                string subject = this._MailFactory.CreateSubject();
                string message = this._MailFactory.CreateBody(executing, completed, failed);

                foreach (Email email in this._EmailRepository.Find(admin))
                {
                    this._MailSender.Send(smtpconfig.Server, smtpconfig.Port, smtpconfig.Username, smtpconfig.Password, smtpconfig.From, email.Address, subject, message, method, protocol);
                }
            }
        }
示例#9
0
        public static void SendMail(
            string smtpServer, string username, string password, int port, bool enableSsl,
            SmtpDeliveryMethod deliveryMethod,
            string to, string cc, string bcc, string subject, string body, bool htmlBody,
            List <string> attachmentFileNames,
            int timeOut = 5
            )
        {
            SmtpClient        smtpClient      = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(username, password);
            MailMessage       message         = new MailMessage();
            MailAddress       fromAddress     = new MailAddress(username);

            // This tricks is what makes ports 465 work with .net framework, here we override 465 with 25, to force throws connection to protected 465
            if (port == 465)
            {
                port = 25;
            }

            smtpClient.Host = smtpServer;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Timeout = (timeOut * 1000);
            // Required for GMail 587,true,SmtpDeliveryMethod.Network
            smtpClient.Port           = port;
            smtpClient.EnableSsl      = enableSsl;
            smtpClient.DeliveryMethod = deliveryMethod;
            // Required to be the last to prevent 5.5.1 Authentication Required, this way we dont need to "enable less secure apps" :)
            smtpClient.Credentials = basicCredential;

            message.From       = fromAddress;
            message.Subject    = subject;
            message.IsBodyHtml = false;
            message.Body       = body;
            if (!string.IsNullOrEmpty(to))
            {
                message.To.Add(to);
            }
            if (!string.IsNullOrEmpty(cc))
            {
                message.CC.Add(cc);
            }
            if (!string.IsNullOrEmpty(bcc))
            {
                message.Bcc.Add(bcc);
            }

            // Enable Html Body
            message.IsBodyHtml = htmlBody;

            // Add Attachment
            foreach (var item in attachmentFileNames)
            {
                message.Attachments.Add(new Attachment(item));
            }

            smtpClient.Send(message);
        }
示例#10
0
 /// <summary>
 /// 发送邮件
 /// </summary>
 /// <param name="from">发送人邮件地址</param>
 /// <param name="fromName">发送人显示名称</param>
 /// <param name="to">发送给谁(邮件地址),多个邮件地址以逗号分割</param>
 /// <param name="subject">标题</param>
 /// <param name="body">内容</param>
 /// <param name="userName">邮件登录名</param>
 /// <param name="password">邮件密码</param>
 /// <param name="attachment">附件</param>
 /// <param name="host">邮件服务器(smtp.126.com)</param>
 /// <param name="port">端口号,默认25</param>
 /// <param name="enableSsl">是否启用SSL加密,默认false</param>
 /// <param name="useDefaultCredentials">是否使用凭据,默认true</param>
 /// <param name="timeout">超时时长,默认10000ms</param>
 /// <param name="bodyEncoding">邮件内容编码方式,默认Encoding.Default</param>
 /// <param name="deliveryMethod">推送方式,默认Network</param>
 /// <returns>bool</returns>
 public static async Task SendMailAsync(
     string from,
     string fromName,
     string to,
     string subject,
     string body,
     string userName,
     string password,
     string attachment,
     string host,
     int port                          = 25,
     bool enableSsl                    = false,
     bool useDefaultCredentials        = true,
     int timeout                       = 10000,
     Encoding bodyEncoding             = null,
     SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network)
 {
     //邮件发送类
     using (var message = new MailMessage())
     {
         //是谁发送的邮件
         message.From = new MailAddress(from, fromName);
         //发送给谁
         message.To.Add(to);
         //标题
         message.Subject = subject;
         //内容编码
         message.BodyEncoding = bodyEncoding ?? Encoding.Default;
         //发送优先级
         message.Priority = MailPriority.High;
         //邮件内容
         message.Body = body;
         //是否HTML形式发送
         message.IsBodyHtml = true;
         //附件
         if (attachment?.Length > 0)
         {
             message.Attachments.Add(new Attachment(attachment));
         }
         //邮件服务器和端口
         using (var client = new SmtpClient(host, port))
         {
             //凭据
             client.UseDefaultCredentials = useDefaultCredentials;
             //ssl加密
             client.EnableSsl = enableSsl;
             //指定发送方式
             client.DeliveryMethod = deliveryMethod;
             //指定登录名和密码
             client.Credentials = new NetworkCredential(userName, password);
             //超时时间
             client.Timeout = timeout;
             await client.SendMailAsync(message);
         }
     }
 }
示例#11
0
 public void Send(MailMessage msg, string host, int port, SmtpDeliveryMethod deliveryMethod)
 {
     using (var client = new SmtpClient())
     {
         client.Host           = SmtpHost;
         client.Port           = SmtpPort;
         client.DeliveryMethod = SmtpDeliveryMethod.Network;
         client.Send(mail);
     }
 }
示例#12
0
 public MailSender(string host, int port, SmtpDeliveryMethod method, string userName, string password, bool useSSL = false)
 {
     _client = new SmtpClient(host, port)
     {
         DeliveryMethod        = method,
         UseDefaultCredentials = false,
         Credentials           = new NetworkCredential(userName, password),
         EnableSsl             = useSSL
     };
 }
示例#13
0
 public static SmtpClient GetSmtpClient(int port, SmtpDeliveryMethod method, string host, bool useDefaultCredentials)
 {
     return(new SmtpClient()
     {
         Port = port,
         DeliveryMethod = method,
         UseDefaultCredentials = useDefaultCredentials,
         Host = host
     });
 }
示例#14
0
 public void Send(MailMessage msg, string host, int port, SmtpDeliveryMethod deliveryMethod)
 {
     using (var client = new SmtpClient())
     {
         client.Host           = host;
         client.Port           = port;
         client.DeliveryMethod = deliveryMethod;
         client.Send(msg);
     }
 }
示例#15
0
 public EmailArg(string from, string tos, string body, string subject, string host, bool useDefaultCredentials, SmtpDeliveryMethod deliveryMethod, int port)
 {
     From    = from;
     Tos     = tos;
     Body    = body;
     Subject = subject;
     Host    = host;
     UseDefaultCredentials = useDefaultCredentials;
     DeliveryMethod        = deliveryMethod;
     Port = port;
 }
示例#16
0
        public static SmtpClient GetSmtpClient(string server, int port, string userName, string password, bool sslEnabled = false,
                                               bool useDefaultCredentials = false, SmtpDeliveryMethod method = SmtpDeliveryMethod.Network)
        {
            SmtpClient client = new SmtpClient(server, port);

            client.UseDefaultCredentials = useDefaultCredentials;
            client.EnableSsl             = sslEnabled;
            client.Credentials           = new System.Net.NetworkCredential(userName, password);
            client.DeliveryMethod        = method;
            return(client);
        }
示例#17
0
        public void MailDeliveryMethod_ReturnsSpecifiedPickupDirectory_WhenNoConfigExists()
        {
            var mockConfigReader = new Mock <IReadConfiguration>(MockBehavior.Strict);

            mockConfigReader.Setup(x => x.GetSection("system.net/mailSettings/smtp"))
            .Returns(null as ConfigurationSection);
            var appConfiguration = new AppConfiguration(mockConfigReader.Object);

            SmtpDeliveryMethod result = appConfiguration.MailDeliveryMethod;

            result.ShouldEqual(SmtpDeliveryMethod.SpecifiedPickupDirectory);
        }
示例#18
0
 public Email(String userName, String userPassword, String host, int port, SmtpDeliveryMethod deliveryMethod, bool useDefaultCredentials)
 {
     _smtpClient = new SmtpClient
     {
         Host                  = host,
         Port                  = port,
         EnableSsl             = true,
         DeliveryMethod        = deliveryMethod,
         UseDefaultCredentials = useDefaultCredentials,
         Credentials           = new NetworkCredential(userName, userPassword)
     };
 }
示例#19
0
 public Sender(string host, int port, bool enableSsl,
     SmtpDeliveryMethod deliveryMethod, bool useDefaultCredentials, NetworkCredential credentials)
 {
     smtp = new SmtpClient
     {
         Host = host,
         Port = port,
         EnableSsl = enableSsl,
         DeliveryMethod = deliveryMethod,
         UseDefaultCredentials = useDefaultCredentials,
         Credentials = credentials
     };
 }
示例#20
0
文件: Mail.cs 项目: Avaruz/Artemisa2
 public Mail(SmtpDeliveryMethod deliveryMethod, string host, bool useDefaultCredentials)
 {
     _smtp = new SmtpClient
     {
         Host = host,
         DeliveryMethod = deliveryMethod,
         UseDefaultCredentials = useDefaultCredentials
     };
     //Or Your SMTP Server Address
     //smtp.Credentials = new NetworkCredential
     //     ("BOMP\asoriagalvarro", "U$umaki2011");
     //Or your Smtp Email ID and Password
 }
示例#21
0
 public MailSettings(SmtpDeliveryMethod deliveryMethod, string fromAddress, string fromName, string host, int port, string userName, string password, bool enableSsl, string replyToAddress)
 {
     this.DeliveryMethod = deliveryMethod;
     this.FromAddress = fromAddress;
     this.FromName = fromName;
     this.Host = host;
     this.Port = port;
     //Me.UseDefaultCredentials = useDefaultCredentials
     this.UserName = userName;
     this.Password = password;
     this.EnableSsl = enableSsl;
     this.ReplyToAddress = replyToAddress;
 }
示例#22
0
 public MailSettings(SmtpDeliveryMethod deliveryMethod, string fromAddress, string fromName, string host, int port, string userName, string password, bool enableSsl, string replyToAddress)
 {
     this.DeliveryMethod = deliveryMethod;
     this.FromAddress    = fromAddress;
     this.FromName       = fromName;
     this.Host           = host;
     this.Port           = port;
     //Me.UseDefaultCredentials = useDefaultCredentials
     this.UserName       = userName;
     this.Password       = password;
     this.EnableSsl      = enableSsl;
     this.ReplyToAddress = replyToAddress;
 }
示例#23
0
 /// <summary>
 /// 设置发件账户信息
 /// </summary>
 /// <param name="posterMail">发件人Email</param>
 /// <param name="posterPwd">发件人Email密码</param>
 /// <param name="posterSmtpHost">发件Email的SMTP地址</param>
 public EmailUtils(string posterMail, string posterPwd, string posterSmtpHost)
 {
     this.PosterMail     = posterMail;
     this.PosterPwd      = posterPwd;
     this.PosterSmtpHost = posterSmtpHost;
     //邮件文本内容默认采用UTF8格式
     this.BodyEncoding = System.Text.Encoding.UTF8;
     //默认允许邮件内容含有HTML内容
     this.IsBodyHtml = true;
     //设置回复Email账户(默认等于发件人Email)
     this.ReplyTo = this.PosterMail;
     //电子邮件发送渠道(通过网络发送)
     this.TheDeliveryMethod = SmtpDeliveryMethod.Network;
 }
示例#24
0
 /// <summary>
 /// 设置发件账户信息
 /// </summary>
 /// <param name="posterMail">发件人Email</param>
 /// <param name="posterPwd">发件人Email密码</param>
 /// <param name="posterSmtpHost">发件Email的SMTP地址</param>
 /// <param name="bodyEncoding">邮件内容编码格式</param>
 /// <param name="isBodyHtml">邮件内容是否允许含有HTML代码</param>
 /// <param name="replyTo">回复邮件地址</param>
 /// <param name="theDeliveryMethod">邮件发送渠道</param>
 public EmailUtils(string posterMail, string posterPwd, string posterSmtpHost, System.Text.Encoding bodyEncoding, bool isBodyHtml, string replyTo, SmtpDeliveryMethod theDeliveryMethod)
 {
     this.PosterMail     = posterMail;
     this.PosterPwd      = posterPwd;
     this.PosterSmtpHost = posterSmtpHost;
     //邮件内容编码格式
     this.BodyEncoding = bodyEncoding;
     //是否允许包含HTML代码
     this.IsBodyHtml = isBodyHtml;
     //设置回复Email账户
     this.ReplyTo = replyTo;
     //电子邮件发送渠道
     this.TheDeliveryMethod = theDeliveryMethod;
 }
示例#25
0
        public void MailDeliveryMethod_ReturnsValue_FromConfig(SmtpDeliveryMethod deliveryMethod)
        {
            var mockConfigReader = new Mock <IReadConfiguration>(MockBehavior.Strict);
            var smtpSection      = new SmtpSection
            {
                DeliveryMethod = deliveryMethod,
            };

            mockConfigReader.Setup(x => x.GetSection("system.net/mailSettings/smtp")).Returns(smtpSection);
            var appConfiguration = new AppConfiguration(mockConfigReader.Object);

            SmtpDeliveryMethod result = appConfiguration.MailDeliveryMethod;

            result.ShouldEqual(deliveryMethod);
        }
示例#26
0
 public void ConfigureSMTPClient(string smtpHost, int smtpPort, SmtpDeliveryMethod smtpDeliveryMetho, bool smtpEnableSsl, bool smtpUseDefaultCredentials, NetworkCredential smtpCredentials)
 {
     try
     {
         smtpclient.Host                  = smtpHost;                  // "smtp.gmail.com";
         smtpclient.Port                  = 587;                       //465; //587;
         smtpclient.DeliveryMethod        = smtpDeliveryMetho;         //System.Net.Mail.SmtpDeliveryMethod.Network;
         smtpclient.EnableSsl             = smtpEnableSsl;             //true;
         smtpclient.UseDefaultCredentials = smtpUseDefaultCredentials; // false;
         smtpclient.Credentials           = smtpCredentials;           // new System.Net.NetworkCredential("*****@*****.**", "xxxpasword");
     }
     catch (Exception ex)
     {
         throw (ex);
     }
 }
示例#27
0
        public SmtpHandler(string host, int port, SmtpDeliveryMethod method, ICredentialsByHost credentials, bool enableSsl)
        {
            this.Host           = host;
            this.Port           = port;
            this.DeliveryMethod = method;
            this.Credentials    = credentials;
            this.EnableSsl      = enableSsl;

            this._smtpClient = new SmtpClient
            {
                Host           = this.Host,
                Port           = this.Port,
                DeliveryMethod = this.DeliveryMethod,
                Credentials    = this.Credentials,
                EnableSsl      = this.EnableSsl,
            };
        }
示例#28
0
 /// <summary>
 /// Construtor
 /// </summary>
 /// <param name="de">Email que será responsável por enviar, caso não seja preenchido será associado o email</param>
 /// <param name="para">Email ou emails (separados por ';') que receberão o e-mail</param>
 /// <param name="porta">Porta para envio do e-mail, caso não seja preenchida será utilizada a 587</param>
 /// <param name="metodoEntrega">Método de entrega do e-mail, caso não seja preenchido será utilizado o: SmtpDeliveryMethod.Network</param>
 /// <param name="host">Host que será enviado o e-mail, caso não seja preenchido será utilizado o</param>
 /// <param name="assunto">Assunto do e-mail</param>
 /// <param name="corpo">Corpo do e-mail</param>
 /// <param name="credenciaisEnvio">Credenciais para o envio do e-mail, caso não seja passada será utilizada as credenciais do email</param>
 /// <param name="corpoHTML">Corpo do e-mail é HTML</param>
 public ConfiguracoesEmail(string para, string assunto, string corpo, string de = "", NetworkCredential credenciaisEnvio = null, int porta = 587, SmtpDeliveryMethod metodoEntrega = SmtpDeliveryMethod.Network, string host = "", bool corpoHtml = false, string nomeExibicao = "")
 {
     De               = de;
     Para             = para;
     Porta            = porta;
     MetodoEntrega    = metodoEntrega;
     Host             = host;
     Assunto          = assunto;
     CorpoHtml        = corpoHtml;
     Corpo            = corpo;
     NomeExibicao     = nomeExibicao;
     CredenciaisEnvio = credenciaisEnvio;
     if (CredenciaisEnvio == null)
     {
         CredenciaisEnvio = new NetworkCredential("email", "senha");
     }
 }
示例#29
0
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //Email

        // Gmail Fix for The server response was: 5.5.1 Authentication Required
        // https://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not
        // go to security settings at the followig link https://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps.
        // https://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not
        //
        //How can I send emails through SSL SMTP with the .NET Framework? - Implicit 465 ?????
        //https://stackoverflow.com/questions/1011245/how-can-i-send-emails-through-ssl-smtp-with-the-net-framework
        //with System.Net.Mail, use port 25 instead of 465:
        //You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.
        public static void SendMail(
            SmtpDeliveryMethod deliveryMethod,
            string to, string cc, string bcc, string subject, string body,
            List <string> attachmentFileNames,
            int timeOut = 5
            )
        {
            // Get Defaults from GlobalFramework.PreferenceParameters
            string smtpServer  = GlobalFramework.PreferenceParameters["SEND_MAIL_SMTP_SERVER"];
            string username    = GlobalFramework.PreferenceParameters["SEND_MAIL_SMTP_USERNAME"];
            string password    = GlobalFramework.PreferenceParameters["SEND_MAIL_SMTP_PASSWORD"];
            int    port        = Convert.ToInt16(GlobalFramework.PreferenceParameters["SEND_MAIL_SMTP_PORT"]);
            bool   enableSsl   = Convert.ToBoolean(GlobalFramework.PreferenceParameters["SEND_MAIL_SMTP_ENABLE_SSL"]);
            bool   useHtmlBody = Convert.ToBoolean(GlobalFramework.PreferenceParameters["SEND_MAIL_FINANCE_DOCUMENTS_HTML_BODY"]);

            SendMail(smtpServer, username, password, port, enableSsl, deliveryMethod, to, cc, bcc, subject, body, useHtmlBody, attachmentFileNames, timeOut);
        }
示例#30
0
 /// <summary>
 /// 默认发件账户信息
 /// </summary>
 public EmailUtils()
 {
     //设置默认发件人Email
     this.PosterMail = string.Empty;
     //设置默认发件人Email密码
     this.PosterPwd = string.Empty;
     //设置默认发件人Email的SMTP邮件服务器
     this.PosterSmtpHost = string.Empty;
     //邮件文本内容默认采用UTF8格式
     this.BodyEncoding = System.Text.Encoding.UTF8;
     //默认允许邮件内容含有HTML内容
     this.IsBodyHtml = true;
     //设置回复Email账户(默认等于发件人Email)
     this.ReplyTo = this.PosterMail;
     //电子邮件发送渠道(通过网络发送)
     this.TheDeliveryMethod = SmtpDeliveryMethod.Network;
 }
示例#31
0
        //ConfigurationManager.AppSettings
        public EmailService(IConfiguration config)
        {
            _port         = Convert.ToInt32(config["EmailSettings:Port"]);
            _host         = config["EmailSettings:Host"];
            _smtpUsername = config["EmailSettings:User"];

            _smtpPassword   = config["EmailSettings:Password"];
            _deliveryMethod =
                (SmtpDeliveryMethod)Enum.Parse(typeof(SmtpDeliveryMethod), config["EmailSettings:DeliveryMethod"]);
            //Network
            //SpecifiedPickupDirectory
            //PickupDirectoryFromIis
            _useDefaultCredentials = Convert.ToBoolean(config["EmailSettings:UseDefaultCredentials"]);
            _isBodyHtml            = Convert.ToBoolean(config["EmailSettings:IsBodyHtml"]);
            _enableSsl             = Convert.ToBoolean(config["EmailSettings:EnableSsl"]);
            _timeout = Convert.ToInt32(config["EmailSettings:Timeout"]);
        }
示例#32
0
        //可以
        public static void SendHotmail()
        {
            //string user = "******";
            //string password = "******";
            //string host = "smtp.live.com";
            //string mailAddress = "*****@hotmail.com";
            IList <string> toAddress = new List <string>();

            toAddress.Add(ToAddress);
            bool enableSsl = true;
            SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network;
            int    post    = 465;
            string title   = "标题";
            string content = "发送内容";
            //MailModel mailModel = new MailModel(user, password, host, mailAddress, toAddress,enableSsl, deliveryMethod, post, title, content);

            //SennMail(mailModel);
        }
示例#33
0
        //[Ignore("Read_SmtpConfig_From_ConfigFile")]
        public void Read_SmtpConfig_From_ConfigFile(SmtpDeliveryMethod smtpDeliveryMethod, bool enableSsl)
        {
            var smtpConfig   = new SmtpClientConfig();
            var smtpSettings = new SmtpSection()
            {
                DeliveryMethod = smtpDeliveryMethod,
                Network        = { EnableSsl = enableSsl }
            };

            ChangeSmtpConfigFile(smtpSettings);
            smtpConfig.ReadSmtpConfigurationFromConfigFile();

            Assert.AreEqual(smtpDeliveryMethod == SmtpDeliveryMethod.Network ? MessageOutput.SmtpServer :
                            smtpDeliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis ? MessageOutput.PickupDirectoryFromIis :
                            smtpDeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory ? MessageOutput.Directory :
                            MessageOutput.None, smtpConfig.MessageOutput);

            Assert.AreEqual(enableSsl ? MailKit.Security.SecureSocketOptions.Auto : MailKit.Security.SecureSocketOptions.None, smtpConfig.SecureSocketOptions);
        }
示例#34
0
        public static void Sender(string host,int smtpport,string fromMail,string fromPassword,string toMail, string toName, string body, string subject,string senderDisplayName="",bool enableSsl = false,SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network,bool useDefaultCredentials = false)
        {
            var fromAddress = new MailAddress(fromMail, senderDisplayName);
            var toAddress = new MailAddress(toMail, toName);

            var smtp = new SmtpClient
            {
                Host = host,
                Port = smtpport,
                EnableSsl = enableSsl,
                DeliveryMethod = deliveryMethod,
                UseDefaultCredentials = useDefaultCredentials,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            };
            smtp.Send(message);
        }
 private void Initialize()
 {
     if ((this.port == defaultPort) || (this.port == 0))
     {
         new SmtpPermission(SmtpAccess.Connect).Demand();
     }
     else
     {
         new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
     }
     this.transport = new SmtpTransport(this);
     if (Logging.On)
     {
         Logging.Associate(Logging.Web, this, this.transport);
     }
     this.onSendCompletedDelegate = new SendOrPostCallback(this.SendCompletedWaitCallback);
     if (MailConfiguration.Smtp != null)
     {
         if (MailConfiguration.Smtp.Network != null)
         {
             if ((this.host == null) || (this.host.Length == 0))
             {
                 this.host = MailConfiguration.Smtp.Network.Host;
             }
             if (this.port == 0)
             {
                 this.port = MailConfiguration.Smtp.Network.Port;
             }
             this.transport.Credentials = MailConfiguration.Smtp.Network.Credential;
             this.transport.EnableSsl = MailConfiguration.Smtp.Network.EnableSsl;
             if (MailConfiguration.Smtp.Network.TargetName != null)
             {
                 this.targetName = MailConfiguration.Smtp.Network.TargetName;
             }
             this.clientDomain = MailConfiguration.Smtp.Network.ClientDomain;
         }
         this.deliveryMethod = MailConfiguration.Smtp.DeliveryMethod;
         if (MailConfiguration.Smtp.SpecifiedPickupDirectory != null)
         {
             this.pickupDirectoryLocation = MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
         }
     }
     if ((this.host != null) && (this.host.Length != 0))
     {
         this.host = this.host.Trim();
     }
     if (this.port == 0)
     {
         this.port = defaultPort;
     }
     if (this.targetName == null)
     {
         this.targetName = "SMTPSVC/" + this.host;
     }
     if (this.clientDomain == null)
     {
         string hostName = IPGlobalProperties.InternalGetIPGlobalProperties().HostName;
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < hostName.Length; i++)
         {
             char ch = hostName[i];
             if (ch <= '\x007f')
             {
                 builder.Append(ch);
             }
         }
         if (builder.Length > 0)
         {
             this.clientDomain = builder.ToString();
         }
         else
         {
             this.clientDomain = "LocalHost";
         }
     }
 }
        private void SendMail(string smtpServer, string @from, string password, string mailto, string caption, string message, int port, bool enableSsl, 
            SmtpDeliveryMethod smtpDeliveryMethod, bool isBodyHtml,
            IEnumerable<Attachment> attachments)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from);
                mail.To.Add(new MailAddress(mailto));
                mail.Subject = caption;
                mail.Body = message;
                mail.IsBodyHtml = isBodyHtml;

                foreach (var attachment in attachments)
                {
                    mail.Attachments.Add(attachment);
                }

                SmtpClient client = new SmtpClient
                {
                    Host = smtpServer,
                    Port = port,
                    EnableSsl = enableSsl,
                    Credentials = new NetworkCredential(@from.Split('@')[0], password),
                    DeliveryMethod = smtpDeliveryMethod
                };
                client.Send(mail);
                mail.Dispose();
            }
            catch (Exception e)
            {
                //throw new Exception("Mail.Send: " + e.Message);
            }
        }
 public SmtpDeliveryMethodType(SmtpDeliveryMethod method, string description)
 {
     mMethod = method;
     mDescription = description;
 }
示例#38
0
 /// <summary>
 /// Sends a RFC conform email using default .NET classes.
 /// </summary>
 /// <param name="fromAddress">Mail-address of the sender.</param>
 /// <param name="toAddress">Mail-address of the receiver.</param>
 /// <param name="subject">Subject of the mail.</param>
 /// <param name="body">The string for the body of the mail.</param>
 /// <param name="settings">A structure containing the settings for the server.</param>
 /// <param name="deliveryMethod">The method for mail delivery to use.</param>
 /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns>        
 public static bool SendMail(string fromAddress, string toAddress, string subject, string body, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network)
 {
     return SendMail(fromAddress, new[] { toAddress }, subject, body, settings, deliveryMethod);
 }
示例#39
0
 private void Initialize()
 {
     if (this.port == SmtpClient.defaultPort || this.port == 0)
     new SmtpPermission(SmtpAccess.Connect).Demand();
       else
     new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
       this.transport = new SmtpTransport(this);
       if (Logging.On)
     Logging.Associate(Logging.Web, (object) this, (object) this.transport);
       this.onSendCompletedDelegate = new SendOrPostCallback(this.SendCompletedWaitCallback);
       if (SmtpClient.MailConfiguration.Smtp != null)
       {
     if (SmtpClient.MailConfiguration.Smtp.Network != null)
     {
       if (this.host == null || this.host.Length == 0)
     this.host = SmtpClient.MailConfiguration.Smtp.Network.Host;
       if (this.port == 0)
     this.port = SmtpClient.MailConfiguration.Smtp.Network.Port;
       this.transport.Credentials = (ICredentialsByHost) SmtpClient.MailConfiguration.Smtp.Network.Credential;
       this.transport.EnableSsl = SmtpClient.MailConfiguration.Smtp.Network.EnableSsl;
       if (SmtpClient.MailConfiguration.Smtp.Network.TargetName != null)
     this.targetName = SmtpClient.MailConfiguration.Smtp.Network.TargetName;
       this.clientDomain = SmtpClient.MailConfiguration.Smtp.Network.ClientDomain;
     }
     this.deliveryFormat = SmtpClient.MailConfiguration.Smtp.DeliveryFormat;
     this.deliveryMethod = SmtpClient.MailConfiguration.Smtp.DeliveryMethod;
     if (SmtpClient.MailConfiguration.Smtp.SpecifiedPickupDirectory != null)
       this.pickupDirectoryLocation = SmtpClient.MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
       }
       if (this.host != null && this.host.Length != 0)
     this.host = this.host.Trim();
       if (this.port == 0)
     this.port = SmtpClient.defaultPort;
       if (this.targetName == null)
     this.targetName = "SMTPSVC/" + this.host;
       if (this.clientDomain != null)
     return;
       string unicode = IPGlobalProperties.InternalGetIPGlobalProperties().HostName;
       IdnMapping idnMapping = new IdnMapping();
       try
       {
     unicode = idnMapping.GetAscii(unicode);
       }
       catch (ArgumentException ex)
       {
       }
       StringBuilder stringBuilder = new StringBuilder();
       for (int index = 0; index < unicode.Length; ++index)
       {
     char ch = unicode[index];
     if ((int) ch <= (int) sbyte.MaxValue)
       stringBuilder.Append(ch);
       }
       if (stringBuilder.Length > 0)
     this.clientDomain = ((object) stringBuilder).ToString();
       else
     this.clientDomain = "LocalHost";
 }
示例#40
0
 /// <summary>
 /// Sends a RFC conform email using default .NET classes.
 /// </summary>
 /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param>
 /// <param name="settings">A structure containing the settings for the server.</param>
 /// <param name="deliveryMethod">The method for mail delivery to use.</param>
 /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns>
 public static bool SendMail(MailMessage messageToSend, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network)
 {
     return SendMailAsync(messageToSend, settings, deliveryMethod).Result;
 }
示例#41
0
 /// <summary>
 /// Sends a RFC conform email using default .NET classes.
 /// </summary>
 /// <param name="fromAddress">Mail-address of the sender.</param>
 /// <param name="toAddresses">Mail-addresses of the receivers.</param>
 /// <param name="subject">Subject of the mail.</param>
 /// <param name="body">The string for the body of the mail.</param>
 /// <param name="settings">A structure containing the settings for the server.</param>
 /// <param name="deliveryMethod">The method for mail delivery to use.</param>
 /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns>       
 public static bool SendMail(string fromAddress, string[] toAddresses, string subject, string body, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network)
 {
     CheckUtil.ThrowIfNullOrWhitespace(() => subject);
     CheckUtil.ThrowIfNullOrWhitespace(() => body);
     var result = false;
     if (!fromAddress.IsValidEmailAddress())
     {
         throw new ArgumentException("Invalid e-mail-address of sender.", nameof(fromAddress));
     }
     if (!toAddresses.Any())
     {
         throw new ArgumentException("No receipient submitted!", nameof(toAddresses));
     }
     if (toAddresses.Any(a => !a.IsValidEmailAddress()))
     {
         throw new ArgumentException("Invalid e-mail-address of on of the recipient.", nameof(toAddresses));
     }
     // Send the mail and use credentials if given.
     using (var message = new MailMessage(fromAddress, toAddresses.First(), subject, body))
     {
         if (toAddresses.Count() > 1)
         {
             // add the other receipients
             for (var i = 1; i < toAddresses.Count(); i++)
             {
                 message.To.Add(toAddresses[i]);
             }
         }
         result = SendMail(message, settings, deliveryMethod);
     }
     return result;
 }
示例#42
0
 public SmtpWrapper(String host, Int32 port, NetworkCredential credentials, SmtpDeliveryMethod deliveryMethod)
 {
     _client = new SmtpClient(host, port) { Credentials = credentials, DeliveryMethod = deliveryMethod };
 }
示例#43
0
 /// <summary>
 /// Sends a RFC conform email using default .NET classes.
 /// </summary>
 /// <param name="messageToSend">The pre-configured <see cref="MailMessage" /> to send.</param>
 /// <param name="settings">A structure containing the settings for the server.</param>
 /// <param name="deliveryMethod">The method for mail delivery to use.</param>
 /// <returns><c>True</c> if the mail was sent, otherwise <c>false</c>.</returns>
 public static async Task<bool> SendMailAsync(MailMessage messageToSend, MailServerSettings settings, SmtpDeliveryMethod deliveryMethod = SmtpDeliveryMethod.Network)
 {
     CheckUtil.ThrowIfNull(() => messageToSend);
     try
     {
         // Send the mail and use credentials if given.
         using (var client = new SmtpClient())
         {
             client.Host = settings.ServerAddress;
             client.Port = settings.Port;
             client.UseDefaultCredentials = settings.UseDefaultCredentials;
             if (settings.UseDefaultCredentials)
             {
                 client.Credentials = CredentialCache.DefaultNetworkCredentials;
             }
             else
             {
                 if (!string.IsNullOrEmpty(settings.Username) && !string.IsNullOrEmpty(settings.Password))
                 {
                     client.Credentials = new NetworkCredential(settings.Username, settings.Password, settings.Domain ?? string.Empty);
                 }
             }
             client.DeliveryMethod = deliveryMethod;                    
             client.EnableSsl = settings.UseSsl;
             await client.SendMailAsync(messageToSend).ConfigureAwait(false);
         }
         return true;
     }
     catch (Exception ex)
     {
         var error = string.Format(
             CultureInfo.InvariantCulture,
             "Cannot send e-mail from '{0}' to '{1}' with subject '{2}': {3}",
             messageToSend.From,
             messageToSend.To,
             messageToSend.Subject,
             ex);
         var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), "mail.error");
         using (var writer = File.AppendText(file))
         {
             writer.Write(error);
             writer.Close();
         }
         throw new InvalidOperationException(error, ex);
     }
 }
示例#44
0
 public void DeliveryMethodTest(SmtpDeliveryMethod method)
 {
     Smtp.DeliveryMethod = method;
     Assert.Equal(method, Smtp.DeliveryMethod);
 }
示例#45
0
 public MailSettings(SmtpDeliveryMethod deliveryMethod, string fromAddress, string fromName, string host, int port, bool enableSsl, string replyToAddress)
     : this(deliveryMethod, fromAddress, fromName, host, port, "*****@*****.**", "r......!", enableSsl, replyToAddress)
 {
 }
示例#46
0
 public SmtpWrapper(string host, int port, NetworkCredential credentials, SmtpDeliveryMethod deliveryMethod)
 {
     this.client = new SmtpClient(host, port) { Credentials = credentials, DeliveryMethod = deliveryMethod };
 }
示例#47
0
        public void MailDeliveryMethod_ReturnsValue_FromConfig(SmtpDeliveryMethod deliveryMethod)
        {
            var mockConfigReader = new Mock<IReadConfiguration>(MockBehavior.Strict);
            var smtpSection = new SmtpSection
            {
                DeliveryMethod = deliveryMethod,
            };
            mockConfigReader.Setup(x => x.GetSection("system.net/mailSettings/smtp")).Returns(smtpSection);
            var appConfiguration = new AppConfiguration(mockConfigReader.Object);

            SmtpDeliveryMethod result = appConfiguration.MailDeliveryMethod;
            result.ShouldEqual(deliveryMethod);
        }
示例#48
0
        void Initialize() {
            if (port == defaultPort || port == 0) {
                new SmtpPermission(SmtpAccess.Connect).Demand();
            }
            else {
                new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand();
            }

            transport = new SmtpTransport(this);
            if (Logging.On) Logging.Associate(Logging.Web, this, transport);
            onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);

            if (MailConfiguration.Smtp != null) 
            {
                if (MailConfiguration.Smtp.Network != null) 
                {
                    if (host == null || host.Length == 0) {
                        host = MailConfiguration.Smtp.Network.Host;
                    }
                    if (port == 0) {
                        port = MailConfiguration.Smtp.Network.Port;
                    }

                    transport.Credentials = MailConfiguration.Smtp.Network.Credential;
                    transport.EnableSsl = MailConfiguration.Smtp.Network.EnableSsl;

                    if (MailConfiguration.Smtp.Network.TargetName != null)
                        targetName = MailConfiguration.Smtp.Network.TargetName;

                    // If the config file contains a domain to be used for the 
                    // domain element in the client's EHLO or HELO message, 
                    // use it.
                    //
                    // We do not validate whether the domain specified is valid.
                    // It is up to the administrators or user to use the right
                    // value for their scenario. 
                    //
                    // Note: per section 4.1.4 of RFC2821, the domain element of 
                    // the HELO/EHLO should be used for logging purposes. An 
                    // SMTP server should not decide to route an email based on
                    // this value.
                    clientDomain = MailConfiguration.Smtp.Network.ClientDomain;
                }

                deliveryFormat = MailConfiguration.Smtp.DeliveryFormat;

                deliveryMethod = MailConfiguration.Smtp.DeliveryMethod;
                if (MailConfiguration.Smtp.SpecifiedPickupDirectory != null)
                    pickupDirectoryLocation = MailConfiguration.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation;
            }

            if (host != null && host.Length != 0) {
                host = host.Trim();
            }

            if (port == 0) {
                port = defaultPort;
            }

            if (this.targetName == null)
                targetName = "SMTPSVC/" + host;

            if (clientDomain == null) {
                // We use the local host name as the default client domain
                // for the client's EHLO or HELO message. This limits the 
                // information about the host that we share. Additionally, the 
                // FQDN is not available to us or useful to the server (internal
                // machine connecting to public server).

                // SMTP RFC's require ASCII only host names in the HELO/EHLO message.
                string clientDomainRaw = IPGlobalProperties.InternalGetIPGlobalProperties().HostName;
                IdnMapping mapping = new IdnMapping();
                try
                {
                    clientDomainRaw = mapping.GetAscii(clientDomainRaw);
                }
                catch (ArgumentException) { }

                // For some inputs GetAscii may fail (bad Unicode, etc).  If that happens
                // we must strip out any non-ASCII characters.
                // If we end up with no characters left, we use the string "LocalHost".  This 
                // matches Outlook behavior.
                StringBuilder sb = new StringBuilder();
                char ch;
                for (int i = 0; i < clientDomainRaw.Length; i++) {
                    ch = clientDomainRaw[i];
                    if ((ushort)ch <= 0x7F)
                        sb.Append(ch);
                }
                if (sb.Length > 0)
                    clientDomain = sb.ToString();
                else
                    clientDomain = "LocalHost";
            }
        }