コード例 #1
0
        public async void Send_WithDefaultFromAddress_Success()
        {
            _smtpClient.Setup(client => client.SendMailAsync(It.IsAny <MailMessage>()))
            .Returns(Task.CompletedTask);

            var provider = new SmtpProvider(
                new SmtpProviderOptions {
                DefaultFromAddress = "*****@*****.**"
            },
                _smtpClient.Object,
                _loggerFactory.Object);

            var message = new EmailMessage
            {
                ToAddresses = new List <string> {
                    "*****@*****.**"
                },
                Subject = "Test Email"
            };

            var result = await provider.Send(message.ToParameters());

            Assert.True(result.IsSuccess);
            Assert.Empty(result.Errors);
        }
コード例 #2
0
        public async void Send_Success()
        {
            _smtpClient.Setup(client => client.SendMailAsync(It.IsAny <MailMessage>()))
            .Returns(Task.CompletedTask);

            var provider = new SmtpProvider(_smtpClient.Object, _loggerFactory.Object);

            var message = new EmailMessage
            {
                FromAddress = "*****@*****.**",
                ToAddresses = new List <string> {
                    "*****@*****.**"
                },
                Subject = "Test Email"
            };

            var result = await provider.Send(message.ToParameters());

            Assert.True(result.IsSuccess);
            Assert.Empty(result.Errors);

            var startMessage = LoggerHelper.FormatLogValues(SmtpLogMessages.Sending_Start, message.Subject, message.ToAddresses);

            _logger.VerifyLog(LogLevel.Debug, startMessage);

            var endMessage = LoggerHelper.FormatLogValues(SmtpLogMessages.Sending_End, message.Subject, message.ToAddresses);

            _logger.VerifyLog(LogLevel.Debug, endMessage);
        }
コード例 #3
0
        public void Send_ThrowException()
        {
            _smtpClient.Setup(client => client.SendMailAsync(It.IsAny <MailMessage>()))
            .Throws(new Exception("Exception01"));

            var provider = new SmtpProvider(_smtpClient.Object, _loggerFactory.Object);

            var message = new EmailMessage
            {
                FromAddress = "*****@*****.**",
                ToAddresses = new List <string> {
                    "*****@*****.**"
                },
                Subject = "Test Email"
            };

            var exception = Record.ExceptionAsync(() => provider.Send(message.ToParameters()));

            Assert.Equal("Exception01", exception.Result.Message);

            var startMessage = LoggerHelper.FormatLogValues(SmtpLogMessages.Sending_Start, message.Subject, message.ToAddresses);

            _logger.VerifyLog(LogLevel.Debug, startMessage);

            var endMessage = LoggerHelper.FormatLogValues(SmtpLogMessages.Sending_End, message.Subject, message.ToAddresses);

            _logger.VerifyLog(LogLevel.Debug, endMessage, Times.Never());
        }
コード例 #4
0
ファイル: SmtpProviderTest.cs プロジェクト: he-dev/reusable
        //[Fact]
        public async Task Can_send_email()
        {
            var smtp = new SmtpProvider();

            var email = new Email <IEmailSubject, IEmailBody>
            {
                From = "*****@*****.**",
                To   = new List <string> {
                    "*****@*****.**"
                },
                CC = new List <string> {
                    "*****@*****.**"
                },
                Subject = new EmailSubject
                {
                    Value = "Test"
                },
                Body = new EmailBody
                {
                    Value = "Hi!"
                }
            };

            using (var response = await smtp.SendEmailAsync(email))
            {
            }
        }
コード例 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddEventBusRabbitMQ(builder =>
            {
                var retryCount = int.Parse(Configuration["EventBusRetryCount"]);

                builder.ConfigureConnection(con =>
                {
                    con.HostName = Configuration["EventBusConnection"];
                    con.UserName = Configuration["EventBusUserName"];
                    con.Password = Configuration["EventBusPassword"];
                });

                builder.SubscriptionClientName = Configuration["EventBusSubscriptionClientName"];
                builder.RetryCount             = retryCount;

                builder.RegisterEventHandler <EmailSendEventHandler>();
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(Configuration["SwaggerDocName"],
                             new Info
                {
                    Title   = Configuration["SwaggerDocTitle"],
                    Version = Configuration["SwaggerDocVersion"]
                });
            });

            services.AddCors(options =>
            {
                options.AddPolicy(Configuration["CorsPolicy"],
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });

            services.AddTransient <IMailService>(sp =>
            {
                var smtpProvider = new SmtpProvider
                {
                    Domain    = Configuration["SmtpDomain"],
                    EnableSSL = Configuration.GetValue <bool>("SmtpEnableSSL"),
                    Login     = Configuration["SmtpLogin"],
                    Password  = Configuration["SmtpPassword"],
                    Port      = Configuration.GetValue <int>("SmtpPort"),
                    TimeOut   = Configuration.GetValue <int>("SmtpTimeOut")
                };

                var logger = sp.GetRequiredService <ILogger <IMailService> >();
                var mailer = new Mailer.MailServices.Mailer(smtpProvider, logger);
                return(mailer);
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
コード例 #6
0
        static async Task <int> Main(string[] args)
        {
            // constants
            const string _smtpServer   = "smtp.gmail.com";
            const int    _smtpPort     = 587;
            const string _smtpUsername = "******";
            const string _smtpPassword = "******";
            const bool   _smtpUseSsl   = true;

            var _emailTo = new[] { "*****@*****.**" }.ToList();
            var _emailFrom    = "*****@*****.**";
            var _emailSubject = "[TakNotify] Test Message";
            var _emailBody    = $"This message was sent from {Environment.MachineName} at {DateTime.Now.ToLongTimeString()}.";
            var _emailIsHtml  = false;

            Console.WriteLine("TakNotify testing...");

            // logger
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Debug).AddConsole();
            });

            // smtp provider
            var emailProvider = new SmtpProvider(new SmtpProviderOptions
            {
                Server   = _smtpServer,
                Port     = _smtpPort,
                Username = _smtpUsername,
                Password = _smtpPassword,
                UseSSL   = _smtpUseSsl
            }, loggerFactory);

            // get notification instance
            var notification = Notification.GetInstance(loggerFactory.CreateLogger <Notification>());

            notification.AddProvider(emailProvider);

            // email message
            var message = new EmailMessage
            {
                ToAddresses = _emailTo,
                FromAddress = _emailFrom,
                Subject     = _emailSubject,
                Body        = _emailBody,
                IsHtml      = _emailIsHtml
            };

            // send the message
            var result = await notification.SendEmailWithSmtp(message);

            return(result.IsSuccess ? 0 : 1);
        }
コード例 #7
0
        public ActionResult SendMessage(ContactFormModel model)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            var umbraco = new UmbracoHelper(UmbracoContext);

            var content = umbraco.TypedContent(model.ContentId);

            //// Get the SMTP notification method from Merchello.  If it has not been configured, return
            if (SmtpProvider != null)
            {
                var method = SmtpProvider.GetAllNotificationGatewayMethods().FirstOrDefault();

                if (method == null)
                {
                    ViewBag.Mode         = ContactFormModel.DisplayMode.Error;
                    ViewBag.ErrorMessage = MvcHtmlString.Create("The SMTP provider does not have a method configured.");

                    return(CurrentUmbracoPage());
                }

                var patterns = new Dictionary <string, IReplaceablePattern>()
                {
                    { "name", new ReplaceablePattern("name", "{{name}}", model.FromName) },
                    { "message", new ReplaceablePattern("message", "{{message}}", model.Message) },
                    { "email", new ReplaceablePattern("email", "{{email}}", model.FromEmail) },
                    { "phone", new ReplaceablePattern("phone", "{{phone}}", model.Phone) }
                };

                var formatter = new PatternReplaceFormatter(patterns);

                var message = new NotificationMessage(method.NotificationMethod.Key, content.GetSafeString("subject"), model.FromEmail)
                {
                    BodyText   = content.GetSafeHtmlString("emailTemplate").ToHtmlString(),
                    Recipients = content.GetSafeString("to")
                };

                MerchelloContext.Current.Gateways.Notification.Send(message, formatter);

                ViewBag.ConfirmationMessage = content.GetSafeHtmlString("confirmationMessage").ToHtmlString();
                ViewBag.ViewMode            = ContactFormModel.DisplayMode.ConfirmationMessage;
            }
            else
            {
                ViewBag.ViewMode     = ContactFormModel.DisplayMode.Error;
                ViewBag.ErrorMessage = MvcHtmlString.Create("The SMTP provider has not been configured.");
            }

            return(CurrentUmbracoPage());
        }
コード例 #8
0
        private static SmtpClient Connect(SmtpProvider provider)
        {
            var client = new SmtpClient
            {
                Port                  = provider.Port,
                EnableSsl             = provider.EnableSSL,
                Timeout               = provider.TimeOut,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Host                  = provider.Host,
                Credentials           = new NetworkCredential(provider.Email, provider.Password)
            };

            return(client);
        }
コード例 #9
0
        public async void Send_WithoutFromAddress_ReturnError()
        {
            var provider = new SmtpProvider(_smtpClient.Object, _loggerFactory.Object);

            var message = new EmailMessage
            {
                ToAddresses = new List <string> {
                    "*****@*****.**"
                },
                Subject = "Test Email"
            };

            var result = await provider.Send(message.ToParameters());

            Assert.False(result.IsSuccess);
            Assert.Equal("From Address should not be empty", result.Errors[0]);
        }
コード例 #10
0
 public CommandController(JobProvider jobProvider, SabProvider sabProvider,
                          SmtpProvider smtpProvider, TwitterProvider twitterProvider,
                          EpisodeProvider episodeProvider, GrowlProvider growlProvider,
                          SeasonProvider seasonProvider, ProwlProvider prowlProvider,
                          XbmcProvider xbmcProvider, PlexProvider plexProvider,
                          NzbgetProvider nzbgetProvider)
 {
     _jobProvider     = jobProvider;
     _sabProvider     = sabProvider;
     _smtpProvider    = smtpProvider;
     _twitterProvider = twitterProvider;
     _episodeProvider = episodeProvider;
     _growlProvider   = growlProvider;
     _seasonProvider  = seasonProvider;
     _prowlProvider   = prowlProvider;
     _xbmcProvider    = xbmcProvider;
     _plexProvider    = plexProvider;
     _nzbgetProvider  = nzbgetProvider;
 }
コード例 #11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);
#if DEBUG
                    #region Симуляция smtp-провайдера
                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    #endregion Симуляция smtp-провайдера
#else
                    #region  еализация собственного smtp-провайдера
                    SmtpProvider smtpp = new SmtpProvider();
                    smtpp.IsBodyHtml  = true;
                    smtpp.IsSSL       = true;
                    smtpp.MessageBody = "<p>Вы получили это письмо потому что кто-то зарегистрировался на сайте invoteco.com и при регистрации указал этот адрес электронной почты.</p>" +
                                        "<p>Если это были Вы, то подтвердите свой e-mail, нажав на ссылку 'Подтвердить'. В противном случае не предпринимайте никаких действий.</p>" +
                                        "<p>После подтверждения e-mail Вы будете перенаправлены на сайт и после входа сможете воспользоваться всей его функциональностью.</p>" + "<a href=" + callbackUrl + ">ПОДТВЕРДИТЬ</a>";
                    smtpp.MessageSubject = "Подтверждение E-mail";
                    smtpp.SenderEmail    = _config.GetValue <string>("SmtpSettings:Senderemail");
                    smtpp.SenderName     = _config.GetValue <string>("SmtpSettings:Sendername");
                    smtpp.SmtpDomain     = _config.GetValue <string>("SmtpSettings:Smtpdomain");
                    smtpp.SmtpPort       = _config.GetValue <int>("SmtpSettings:Smtpport");
                    smtpp.UserEmail      = user.Email;
                    if (smtpp.IsValidPatch())//Если путь к корневой директории соответствует установленному хостинг-провайдером,
                    {
                        //то отправляем пользователю письмо со ссылкой для подтверждения e-mail.
                        await smtpp.AsyncSendMailWithEncodeUrlPassworFree(smtpp.SenderName, smtpp.SenderEmail, smtpp.UserEmail, smtpp.MessageSubject, smtpp.MessageBody, smtpp.IsBodyHtml, smtpp.SmtpDomain, smtpp.SmtpPort, smtpp.IsSSL);
                    }
                    else
                    {
                        //В противном слуае отправляем письмо о проблеме администратору.
                        string WarningSubject = "Внимание!";
                        string AdminEmail     = _config.GetValue <string>("SmtpSettings:Adminemail");
                        string WarningMessage = "Письма для подтверждения e-mail не доставляются. Проверьте настройки.";

                        await smtpp.AsyncSendMailWithEncodeUrlPassworFree(smtpp.SenderName, smtpp.SenderEmail, AdminEmail, WarningSubject, WarningMessage, smtpp.IsBodyHtml, smtpp.SmtpDomain, smtpp.SmtpPort, smtpp.IsSSL);
                    }
                    #endregion  еализация собственного smtp-провайдера
#endif //DEBUG
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        #region Присвоение первому пользователю [email protected] роли "Admin"
                        //Метод CreateRolesAndAssignToUser в данном случае вызывается для того, чтобы создать перврго пользователя с ролью Admin.
                        //Этот пользователь создается при регистрации с учетными данными (email), указанными в аргументах метода. До его создания (и после)
                        //в приложении может регистрироваться сколько угодно пользователей.
                        await CreateRolesAndAssignToUser(
                            user,
                            _context,
                            _roleManager,
                            _userManager,
                            _config.GetValue <string>("SmtpSettings:Adminname"),
                            _config.GetValue <string>("SmtpSettings:Adminemail"),
                            AdminRoleDescription);

                        #endregion Присвоение первому пользователю [email protected] роли "Admin"

                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            return(Page());
        }
コード例 #12
0
        private static void StartEmailing()
        {
            var useEnvVar = GetYesNoInput("Should I use environment variables? (y/n): ") ?? default;

            string host;
            string port;
            string username;
            string password;

            if (useEnvVar)
            {
                host     = Environment.GetEnvironmentVariable(nameof(host));
                port     = Environment.GetEnvironmentVariable(nameof(port));
                username = Environment.GetEnvironmentVariable(nameof(username));
                password = Environment.GetEnvironmentVariable(nameof(password));
            }
            else
            {
                Console.Write("Please enter your host name: ");
                host = Console.ReadLine();
                var portIndex = host?.IndexOf(":", StringComparison.Ordinal);
                if (portIndex > -1)
                {
                    port = host.Substring(portIndex.Value + 1);
                }
                else
                {
                    Console.Write("Please enter your port: ");
                    port = Console.ReadLine();
                }

                Console.Write("Please enter your username: ");
                username = Console.ReadLine();
                password = MaskPassword();
            }

            if (string.IsNullOrWhiteSpace(host))
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (string.IsNullOrWhiteSpace(port) || !int.TryParse(port, out var actualPort))
            {
                throw new ArgumentNullException(nameof(port));
            }

            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            var smtpProvider = new SmtpProvider(new MailSettings()
            {
                Host     = host,
                Port     = actualPort,
                Username = username,
                Password = password
            });

            RepeatUntilStopped(smtpProvider);
        }
コード例 #13
0
 /// <summary>
 /// Конфигурация.
 /// </summary>
 /// <param name="provider"> Провайдер. </param>
 public Mailer(SmtpProvider provider, ILogger <IMailService> logger)
 {
     _logger   = logger;
     _provider = provider;
     _client   = Connect(provider);
 }
コード例 #14
0
        private static void StartMailer(string email, string ccAddress, string subject, string content, string txnId, int mailType, string username, long user_id, int type)
        {
            mailType = 1;
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += (s, e) =>
            {
                tb_email_logs log = new tb_email_logs();
                try
                {
                    log = MailerContext.LogEmail(new tb_email_logs()
                    {
                        cc               = ccAddress ?? "",
                        content          = HttpUtility.UrlDecode(content ?? ""),
                        error            = "",
                        has_attachement  = false,
                        subject          = subject ?? "",
                        to               = email ?? "",
                        log_entered_date = DateTime.UtcNow,
                        user_identifier  = user_id.ToString()
                    });
                }
                catch (Exception)
                {
                }

                try
                {
                    var smtp = SmtpProvider.GetSmtpSettingFor(mailType);
                    // TODO : Fetch the details from the Web-Admin
                    MailMessage message = new MailMessage();
                    if (email.Contains(";"))
                    {
                        message.From = new MailAddress(smtp.FromAddress);
                        foreach (var item in email.Split(';'))
                        {
                            if (string.IsNullOrEmpty(item))
                            {
                                continue;
                            }
                            message.To.Add(new MailAddress(item));
                        }
                        message.Subject = subject;
                        message.Body    = HttpUtility.UrlDecode(content);
                    }
                    else if (email.Contains(","))
                    {
                        message.From = new MailAddress(smtp.FromAddress);
                        foreach (var item in email.Split(','))
                        {
                            if (string.IsNullOrEmpty(item))
                            {
                                continue;
                            }
                            message.To.Add(new MailAddress(item));
                        }
                        message.Subject = subject;
                        message.Body    = HttpUtility.UrlDecode(content);
                    }
                    else
                    {
                        message = new MailMessage(smtp.FromAddress, email, subject, HttpUtility.UrlDecode(content));
                    }

                    message.IsBodyHtml = true;
                    //message.Attachments.Add(attachment);
                    SmtpClient cnt = new SmtpClient(smtp.Address, Convert.ToInt16(smtp.Port));
                    cnt.Timeout = 2000000;
                    cnt.UseDefaultCredentials = false;
                    cnt.EnableSsl             = true;
                    //cnt.Host = smtp.Address;

                    if (!smtp.UseAnonymous)
                    {
                        cnt.Credentials = new System.Net.NetworkCredential(smtp.UserName, smtp.Password);
                    }
                    cnt.Send(message);
                }
                catch (Exception ex)
                {
                    try
                    {
                        e.Result  = email;
                        log.error = ex.ToString();
                        MailerContext.UpdateEmailLog(log);
                    }
                    catch (Exception)
                    {
                    }
                    //throw ex;
                }
            };
            worker.RunWorkerAsync();
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }
コード例 #15
0
 public Smtp(ConfigProvider configProvider, SmtpProvider smtpProvider)
     : base(configProvider)
 {
     _smtpProvider = smtpProvider;
 }
コード例 #16
0
ファイル: Smtp.cs プロジェクト: Normmatt/NzbDrone
 public Smtp(ConfigProvider configProvider, SmtpProvider smtpProvider)
     : base(configProvider)
 {
     _smtpProvider = smtpProvider;
 }