Пример #1
0
        internal GenericAPI(RoamingNetwork RoamingNetwork,
                            String HTTPServerName = DefaultHTTPServerName,
                            IPPort HTTPServerPort = null,
                            String URIPrefix      = "",
                            Func <String, Stream> GetRessources = null,

                            String ServiceName                = DefaultHTTPServerName,
                            EMailAddress APIEMailAddress      = null,
                            PgpPublicKeyRing APIPublicKeyRing = null,
                            PgpSecretKeyRing APISecretKeyRing = null,
                            String APIPassphrase              = null,
                            EMailAddressList APIAdminEMail    = null,
                            SMTPClient APISMTPClient          = null,

                            DNSClient DNSClient = null,
                            String LogfileName  = DefaultLogfileName)

            : this(RoamingNetwork,
                   new HTTPServer(DefaultServerName : DefaultHTTPServerName).AttachTCPPorts(HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort),
                   URIPrefix,
                   GetRessources,

                   ServiceName,
                   APIEMailAddress,
                   APIPublicKeyRing,
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   LogfileName)

        {
        }
Пример #2
0
        public NewMail()
        {
            InitializeComponent();

            smtp = new SMTPClient(settings.SMTPServer, settings.SMTPPort, settings.SMTPSSL);
            smtp.Authenticate(settings.Username, settings.Password);
        }
Пример #3
0
        public async Task <IActionResult> Edit(Guid id, [Bind("Port,Email,Password,Host,Id,Name,Active")] SMTPClient sMTPClient)
        {
            if (id != sMTPClient.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(sMTPClient);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SMTPClientExists(sMTPClient.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(sMTPClient));
        }
Пример #4
0
        /// <summary>
        /// 是否登录过,记住了密码
        /// </summary>
        /// <returns>登录过返回对象,否则返回null</returns>
        public static bool IsEverLoggedIn()
        {
            DirectoryInfo dir = new DirectoryInfo(SerializeUtil.Dir);

            if (!Directory.Exists(SerializeUtil.Dir))
            {
                Directory.CreateDirectory(SerializeUtil.Dir);
            }
            FileInfo[] infos = dir.GetFiles();
            //是否登录过
            if (infos.Length != 0) //是
            {
                foreach (FileInfo info in infos)
                {
                    //获得用户信息
                    User user = SerializeUtil.DeSerializeUser(info.FullName);
                    if (user.isLogin)
                    {
                        POP3Client pop3Client = new POP3Client(user);
                        SMTPClient smtpClient = new SMTPClient(user);
                        DataService.pop3 = pop3Client;
                        DataService.smtp = smtpClient;
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #5
0
        public async Task <IActionResult> UpdateGrade([FromBody] UpdateGradeModel updateGradeModel, Guid id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var grade = await gradeService.FindById(id);

            if (grade == null)
            {
                return(NotFound());
            }

            var gradeModel = Mapper.Map <UpdateGradeModel, Grade>(updateGradeModel);

            await gradeService.Update(id, gradeModel);

            var updatedGrade = await gradeService.FindById(id);

            var student = await studentService.FindById(updatedGrade.Student.Id);

            SMTPClient.ProfessorSendMailUpdate(updatedGrade, student);

            return(NoContent());
        }
Пример #6
0
        public bool ProcessMail(SendableMail mail)
        {
            var success = true;

            foreach (var connInfo in GroupByHost(mail))
            {
                var addresses = connInfo.Addresses.Select(a => a.Address).ToArray();
                var connector = connInfo.Connector;

                var client = SMTPClient.Create(_container, connector, connInfo.Host, connInfo.Port);

                if (!client.Connect())
                {
                    success = false;

                    TriggerMailError(mail, connInfo, client.LastStatus, client.LastException);
                    continue;
                }

                if (!client.SendMail(mail.From.Address, addresses, mail.ToString()))
                {
                    success = false;

                    TriggerMailError(mail, connInfo, client.LastStatus, client.LastException);
                }

                client.Close();

                // TODO
            }

            return(success);
        }
Пример #7
0
        /// <summary>
        /// Create an instance of the OCPI HTTP API for Charge Point Operators
        /// using a newly created HTTP server.
        /// </summary>
        public CPOAPI(RoamingNetwork RoamingNetwork,
                      String HTTPServerName = DefaultHTTPServerName,
                      IPPort HTTPServerPort = null,
                      String URIPrefix      = "",

                      String ServiceName                = DefaultHTTPServerName,
                      EMailAddress APIEMailAddress      = null,
                      PgpSecretKeyRing APISecretKeyRing = null,
                      String APIPassphrase              = null,
                      EMailAddressList APIAdminEMail    = null,
                      SMTPClient APISMTPClient          = null,

                      DNSClient DNSClient = null,
                      String LogfileName  = DefaultLogfileName)

            : base(RoamingNetwork,
                   HTTPServerName,
                   HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort,
                   URIPrefix,
                   ResourceName => typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot." + ResourceName),

                   ServiceName,
                   APIEMailAddress,
                   null,//OpenPGP.ReadPublicKeyRing(typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.GenericAPI.HTTPRoot.robot@offenes-jena_pubring.gpg")),
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   DNSClient,
                   LogfileName)

        {
            RegisterCPOURITemplates();
        }
Пример #8
0
        public void SMTPClient_ConfigurationInit_Tests()
        {
            // Arrange
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"{
                ""SMTP"": {
                    ""Host"": ""smtp.exmail.qq.com"",
                    ""Port"": 465,
                    ""UseSsl"": true,
                    ""UserName"": ""*****@*****.**"",
                    ""Password"": ""***""
                }
            }"));
            var section = new ConfigurationBuilder().AddJsonStream(stream).Build().GetSection("SMTP");

            var client = new SMTPClient(section);

            // Act
            var result = Assert.ThrowsAsync <AuthenticationException>(async() =>
            {
                await client.SendAsync(message);
            });

            // Assert
            Assert.IsTrue(result?.Message.StartsWith("535:"));
        }
Пример #9
0
        /// <summary>
        /// Initialize the OCPI HTTP server using IPAddress.Any, http port 8080 and maybe start the server.
        /// </summary>
        internal GenericAPI(RoamingNetwork RoamingNetwork,
                            HTTPServer HTTPServer,
                            String URIPrefix = "/ext/OCPI",
                            Func <String, Stream> GetRessources = null,

                            String ServiceName                = DefaultHTTPServerName,
                            EMailAddress APIEMailAddress      = null,
                            PgpPublicKeyRing APIPublicKeyRing = null,
                            PgpSecretKeyRing APISecretKeyRing = null,
                            String APIPassphrase              = null,
                            EMailAddressList APIAdminEMail    = null,
                            SMTPClient APISMTPClient          = null,

                            String LogfileName = DefaultLogfileName)

        {
            #region Initial checks

            if (RoamingNetwork == null)
            {
                throw new ArgumentNullException("RoamingNetwork", "The given parameter must not be null!");
            }

            if (HTTPServer == null)
            {
                throw new ArgumentNullException("HTTPServer", "The given parameter must not be null!");
            }

            if (URIPrefix.IsNullOrEmpty())
            {
                throw new ArgumentNullException("URIPrefix", "The given parameter must not be null or empty!");
            }

            if (!URIPrefix.StartsWith("/"))
            {
                URIPrefix = "/" + URIPrefix;
            }

            #endregion

            #region Init data

            this._HTTPServer    = HTTPServer;
            this._GetRessources = GetRessources;
            this._URIPrefix     = URIPrefix;

            this._ServiceName      = ServiceName;
            this._APIEMailAddress  = APIEMailAddress;
            this._APIPublicKeyRing = APIPublicKeyRing;
            this._APISecretKeyRing = APISecretKeyRing;
            this._APIPassphrase    = APIPassphrase;
            this._APIAdminEMail    = APIAdminEMail;
            this._APISMTPClient    = APISMTPClient;

            this._DNSClient = HTTPServer.DNSClient;

            #endregion

            RegisterURITemplates();
        }
Пример #10
0
        public async Task <ServiceContract> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new ServiceContract(StatusCodes.Status400BadRequest, null, "Bad Model"));
            }

            var user = new ApplicationUser {
                Email = model.Email, UserName = model.Email, Role = model.Role
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                var cToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var cTokenLink = Url.Action("ConfirmEmail", "Account", new
                {
                    userId = user.Id,
                    token  = cToken
                }, protocol: Request.Scheme);
                SMTPClient.SendConfirmationEmail(user.Email, cTokenLink);

                var resultModel = new ResultModel(user.Id, GenerateJwtToken(user.Email, user), user.Role, user.Email);
                return(new ServiceContract(StatusCodes.Status201Created, resultModel, "User created succesfully"));
            }
            else
            {
                return(new ServiceContract(StatusCodes.Status422UnprocessableEntity, null, "User already exists"));
            }
        }
Пример #11
0
        public NewMail(List <string> to, string subject)
        {
            InitializeComponent();

            toTextBox.Text      = String.Join(",", to.ToArray());
            subjectTextBox.Text = subject;

            smtp = new SMTPClient(settings.SMTPServer, settings.SMTPPort, settings.SMTPSSL);
            smtp.Authenticate(settings.Username, settings.Password);
        }
Пример #12
0
        public static bool LoginSMTP(User user)
        {
            SMTPClient smtpClient = new SMTPClient(user);

            if (smtpClient.Login(user))
            {
                DataService.smtp = smtpClient;
                return(true);
            }
            return(false);
        }
Пример #13
0
        public async Task <IActionResult> SendMail(Guid id)
        {
            var studentModelDetails = await studentService.FindById(id);

            if (studentModelDetails == null)
            {
                return(NotFound());
            }

            SMTPClient.StudentSendMail(studentModelDetails);
            return(Ok());
        }
Пример #14
0
        public async Task <IActionResult> Create([Bind("Port,Email,Password,Host,Id,Name,Active")] SMTPClient sMTPClient)
        {
            if (ModelState.IsValid)
            {
                sMTPClient.Id = Guid.NewGuid();
                _context.Add(sMTPClient);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(sMTPClient));
        }
Пример #15
0
        public void EmailUtilSend_Test()
        {
            // Arrange
            var client = new SMTPClient(new SMTPClientSettings("smtp.exmail.qq.com", 465, true, "ETSOO <*****@*****.**>", "*****@*****.**", "***"));

            // Act
            var result = Assert.ThrowsAsync <AuthenticationException>(async() =>
            {
                await client.SendAsync(message);
            });

            // Assert
            Assert.IsTrue(result?.Message.StartsWith("535:"));
        }
Пример #16
0
        public static bool CreateEvento(Evento evento)
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.DB))
                {
                    conn.Open();
                    using (MySqlCommand sqlCommand = new MySqlCommand("INSERT INTO `evento` (idOrador, nomeEvento, dataEvento, localEvento, tipoEvento, observacoes, notifica, corpomail) VALUES (@idOrador, @nomeEvento, @dataEvento, @localEvento, @tipoEvento, @observacoes, @notifica, @corpomail)", conn))
                    {
                        if (evento.idOrador == 0)
                        {
                            sqlCommand.Parameters.AddWithValue("@idOrador", DBNull.Value);
                        }
                        else
                        {
                            sqlCommand.Parameters.AddWithValue("@idOrador", evento.idOrador);
                        }
                        sqlCommand.Parameters.AddWithValue("@nomeEvento", evento.nomeEvento);
                        sqlCommand.Parameters.AddWithValue("@dataEvento", evento.dataEvento);
                        sqlCommand.Parameters.AddWithValue("@localEvento", evento.localEvento);
                        sqlCommand.Parameters.AddWithValue("@tipoEvento", evento.tipoEvento);
                        sqlCommand.Parameters.AddWithValue("@observacoes", evento.observacoes);
                        sqlCommand.Parameters.AddWithValue("@notifica", evento.notifica);
                        sqlCommand.Parameters.AddWithValue("@corpomail", evento.corpoEmail);

                        sqlCommand.ExecuteNonQuery();
                    }

                    if (evento.notifica)
                    {
                        SMTPClient.NotificacaoEventoEmail(evento);
                    }


                    conn.Close();
                }

                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Erro ao criar Evento: " + e.Message);
                return(false);
            }
        }
Пример #17
0
        public async Task <IActionResult> CreateGrade([FromBody] CreatingGradeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var gradeId = await gradeService.CreateNew(model);

            if (gradeId == default(Guid))
            {
                return(StatusCode(StatusCodes.Status422UnprocessableEntity));
            }

            var gradeModel = await gradeService.FindById(gradeId);

            var student = await studentService.FindById(gradeModel.Student.Id);

            SMTPClient.ProfessorSendMail(gradeModel, student);
            return(StatusCode(StatusCodes.Status201Created));
        }
Пример #18
0
        public async Task <ServiceContract> ForgotPassword([FromBody] ForgotPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new ServiceContract(StatusCodes.Status400BadRequest, null, "Bad Model"));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                return(new ServiceContract(StatusCodes.Status404NotFound, null, "User hasn't been found"));
            }
            var rToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            var rTokenLink = Url.Action("ForgotPasswordConfirmation", "Account", new
            {
                userId = user.Id,
                token  = rToken
            }, protocol: Request.Scheme);

            SMTPClient.SendResetPasswordEmail(model.Email, rTokenLink);
            return(new ServiceContract(StatusCodes.Status200OK, null, "Email to reset password has been sent"));
        }
Пример #19
0
        public Worker(ILogger <Worker> logger, IConfiguration configuration)
        {
            Worker.Logger = logger;
            Worker.Logger.LogInformation("Folder: " + Directory.GetCurrentDirectory());

            repo    = new LocalDbRepo.ListRepoContext();
            threads = new Dictionary <Guid, Thread>();

            var s = new SmtpSettings
            {
                EmailSender    = configuration.GetValue <string>("SMTP:EmailSender"),
                Server         = configuration.GetValue <string>("SMTP:Server"),
                Port           = configuration.GetValue <int>("SMTP:Port"),
                Username       = configuration.GetValue <string>("SMTP:Username"),
                SenderPassword = configuration.GetValue <string>("SMTP:Password")
            };

            SmtpClient = new SMTPClient(s);

            timer          = new System.Timers.Timer();
            timer.Interval = 10000;
            timer.Elapsed += Timer_Elapsed;;
            timer.Start();
        }
Пример #20
0
        /// <summary>
        /// Create an instance of the Open Charging Cloud API.
        /// </summary>
        /// <param name="ServiceName">The name of the service.</param>
        /// <param name="HTTPServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="LocalHostname">The HTTP hostname for all URIs within this API.</param>
        /// <param name="LocalPort">A TCP port to listen on.</param>
        /// <param name="ExternalDNSName">The offical URL/DNS name of this service, e.g. for sending e-mails.</param>
        /// <param name="URLPathPrefix">A common prefix for all URLs.</param>
        ///
        /// <param name="ServerCertificateSelector">An optional delegate to select a SSL/TLS server certificate.</param>
        /// <param name="ClientCertificateValidator">An optional delegate to verify the SSL/TLS client certificate used for authentication.</param>
        /// <param name="ClientCertificateSelector">An optional delegate to select the SSL/TLS client certificate used for authentication.</param>
        /// <param name="AllowedTLSProtocols">The SSL/TLS protocol(s) allowed for this connection.</param>
        ///
        /// <param name="APIEMailAddress">An e-mail address for this API.</param>
        /// <param name="APIPassphrase">A GPG passphrase for this API.</param>
        /// <param name="APIAdminEMails">A list of admin e-mail addresses.</param>
        /// <param name="APISMTPClient">A SMTP client for sending e-mails.</param>
        ///
        /// <param name="SMSAPICredentials">The credentials for the SMS API.</param>
        /// <param name="SMSSenderName">The (default) SMS sender name.</param>
        /// <param name="APIAdminSMS">A list of admin SMS phonenumbers.</param>
        ///
        /// <param name="TelegramBotToken">The Telegram API access token of the bot.</param>
        ///
        /// <param name="CookieName">The name of the HTTP Cookie for authentication.</param>
        /// <param name="UseSecureCookies">Force the web browser to send cookies only via HTTPS.</param>
        /// <param name="Language">The main language of the API.</param>
        /// <param name="NewUserSignUpEMailCreator">A delegate for sending a sign-up e-mail to a new user.</param>
        /// <param name="NewUserWelcomeEMailCreator">A delegate for sending a welcome e-mail to a new user.</param>
        /// <param name="ResetPasswordEMailCreator">A delegate for sending a reset password e-mail to a user.</param>
        /// <param name="PasswordChangedEMailCreator">A delegate for sending a password changed e-mail to a user.</param>
        /// <param name="MinUserNameLength">The minimal user name length.</param>
        /// <param name="MinRealmLength">The minimal realm length.</param>
        /// <param name="PasswordQualityCheck">A delegate to ensure a minimal password quality.</param>
        /// <param name="SignInSessionLifetime">The sign-in session lifetime.</param>
        ///
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        ///
        /// <param name="SkipURLTemplates">Skip URI templates.</param>
        /// <param name="DisableNotifications">Disable external notifications.</param>
        /// <param name="DisableLogfile">Disable the log file.</param>
        /// <param name="LoggingPath">The path for all logfiles.</param>
        /// <param name="LogfileName">The name of the logfile for this API.</param>
        /// <param name="DNSClient">The DNS client of the API.</param>
        /// <param name="Autostart">Whether to start the API automatically.</param>
        public OpenChargingCloudCSOAPI(String ServiceName         = "GraphDefined Open Charging Cloud CSO API",
                                       String HTTPServerName      = "GraphDefined Open Charging Cloud CSO API",
                                       HTTPHostname?LocalHostname = null,
                                       IPPort?LocalPort           = null,
                                       String ExternalDNSName     = null,
                                       HTTPPath?URLPathPrefix     = null,
                                       String HTMLTemplate        = null,
                                       JObject APIVersionHashes   = null,

                                       ServerCertificateSelectorDelegate ServerCertificateSelector    = null,
                                       RemoteCertificateValidationCallback ClientCertificateValidator = null,
                                       LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                                       SslProtocols AllowedTLSProtocols = SslProtocols.Tls12,

                                       EMailAddress APIEMailAddress    = null,
                                       String APIPassphrase            = null,
                                       EMailAddressList APIAdminEMails = null,
                                       SMTPClient APISMTPClient        = null,

                                       Credentials SMSAPICredentials         = null,
                                       String SMSSenderName                  = null,
                                       IEnumerable <PhoneNumber> APIAdminSMS = null,

                                       String TelegramBotToken = null,

                                       HTTPCookieName?CookieName = null,
                                       Boolean UseSecureCookies  = true,
                                       Languages?Language        = null,
                                       NewUserSignUpEMailCreatorDelegate NewUserSignUpEMailCreator     = null,
                                       NewUserWelcomeEMailCreatorDelegate NewUserWelcomeEMailCreator   = null,
                                       ResetPasswordEMailCreatorDelegate ResetPasswordEMailCreator     = null,
                                       PasswordChangedEMailCreatorDelegate PasswordChangedEMailCreator = null,
                                       Byte?MinLoginLength    = null,
                                       Byte?MinRealmLength    = null,
                                       Byte?MinUserNameLength = null,
                                       PasswordQualityCheckDelegate PasswordQualityCheck = null,
                                       TimeSpan?SignInSessionLifetime = null,

                                       String ServerThreadName                 = null,
                                       ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                                       Boolean ServerThreadIsBackground        = true,
                                       ConnectionIdBuilder ConnectionIdBuilder = null,
                                       ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                                       ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                                       Boolean ConnectionThreadsAreBackground = true,
                                       TimeSpan?ConnectionTimeout             = null,
                                       UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,

                                       TimeSpan?MaintenanceEvery       = null,
                                       Boolean DisableMaintenanceTasks = false,

                                       Boolean SkipURLTemplates     = false,
                                       Boolean DisableNotifications = false,
                                       Boolean DisableLogfile       = false,
                                       String DatabaseFile          = DefaultOpenChargingCloudAPIDatabaseFile,
                                       String LoggingPath           = null,
                                       String LogfileName           = DefaultOpenChargingCloudAPILogFile,
                                       DNSClient DNSClient          = null,
                                       Boolean Autostart            = false)

            : base(ServiceName ?? "GraphDefined Open Charging Cloud CSO API",
                   HTTPServerName ?? "GraphDefined Open Charging Cloud CSO API",
                   LocalHostname,
                   LocalPort,
                   ExternalDNSName,
                   URLPathPrefix,
                   HTMLTemplate,
                   APIVersionHashes,

                   ServerCertificateSelector,
                   ClientCertificateValidator,
                   ClientCertificateSelector,
                   AllowedTLSProtocols,

                   APIEMailAddress,
                   APIPassphrase,
                   APIAdminEMails,
                   APISMTPClient,

                   SMSAPICredentials,
                   SMSSenderName ?? "Open Charging Cloud",
                   APIAdminSMS,

                   TelegramBotToken,

                   CookieName ?? HTTPCookieName.Parse("OpenChargingCloudCSOAPI"),
                   UseSecureCookies,
                   Language,
                   NewUserSignUpEMailCreator,
                   NewUserWelcomeEMailCreator,
                   ResetPasswordEMailCreator,
                   PasswordChangedEMailCreator,
                   MinLoginLength,
                   MinRealmLength,
                   MinUserNameLength,
                   PasswordQualityCheck,
                   SignInSessionLifetime,

                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,

                   MaintenanceEvery,
                   DisableMaintenanceTasks,

                   SkipURLTemplates,
                   DisableNotifications,
                   DisableLogfile,
                   DatabaseFile ?? DefaultOpenChargingCloudCSOAPIDatabaseFile,
                   LoggingPath ?? "default",
                   LogfileName ?? DefaultOpenChargingCloudCSOAPILogFile,
                   DNSClient,
                   false)

        {
            //RegisterURLTemplates();

            if (Autostart)
            {
                Start();
            }
        }
Пример #21
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("SendEmail Function triggered by HTTP request.");

            #region ParseRequestBody
            log.LogInformation("Parsing body from request.");

            string  requestBody  = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data         = JsonConvert.DeserializeObject(requestBody);
            string  outputString = string.Empty;
            JObject outputJson;

            string toRecipients     = data?.emailRecipients;
            string ccRecipients     = data?.emailCcRecipients;
            string bccRecipients    = data?.emailBccRecipients;
            string subject          = data?.emailSubject;
            string message          = data?.emailBody;
            string passedImportance = data?.emailImportance ?? ""; //Set normal importance if not provided.
            #endregion

            #region ValidateRequestBody
            //Check for minimum mailing values in request body
            if (subject == null || message == null)
            {
                log.LogInformation("Invalid body - Subject/Body.");

                outputString = "{ \"EmailSent\": false, \"Details\": \"Email subject or body values missing.\"}";
                outputJson   = JObject.Parse(outputString);

                return(new BadRequestObjectResult(outputJson));
            }

            if (
                (toRecipients == null && ccRecipients == null && bccRecipients == null) ||
                (string.IsNullOrEmpty(toRecipients) && string.IsNullOrEmpty(ccRecipients) && string.IsNullOrEmpty(bccRecipients))
                )
            {
                log.LogInformation("Invalid body - To/CC/BCC.");

                outputString = "{ \"EmailSent\": false, \"Details\": \"No email recipients provided as To/CC/BCC.\"}";
                outputJson   = JObject.Parse(outputString);

                return(new BadRequestObjectResult(outputJson));
            }
            #endregion

            //Create email client
            log.LogInformation("Creating smtp client.");

            using (var client = SMTPClient.CreateSMTPClient())
            {
                #region CreateMail
                MailAddress from = new MailAddress(SMTPClient.FromEmail);
                MailMessage mail = new MailMessage
                {
                    From       = from,
                    IsBodyHtml = true,
                    Subject    = subject,
                    Body       = message
                };

                //Set mail importance
                if (passedImportance.ToUpper() == "HIGH")
                {
                    mail.Priority = MailPriority.High;
                }
                else if (passedImportance.ToUpper() == "LOW")
                {
                    mail.Priority = MailPriority.Low;
                }
                else
                {
                    mail.Priority = MailPriority.Normal;
                }
                #endregion

                #region SetRecipients
                //to recipients
                if (!string.IsNullOrEmpty(toRecipients))
                {
                    var allRecipients = toRecipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var toAddress in allRecipients)
                    {
                        mail.To.Add(toAddress);
                    }
                    log.LogInformation("To Recipients Added: " + allRecipients.Count().ToString());
                }
                else
                {
                    log.LogInformation("To Recipients Added: 0");
                }

                //cc recipients
                if (!string.IsNullOrEmpty(ccRecipients))
                {
                    var allCcRecipients = ccRecipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var ccAddress in allCcRecipients)
                    {
                        mail.CC.Add(ccAddress);
                    }
                    log.LogInformation("CC Recipients Added: " + allCcRecipients.Count().ToString());
                }
                else
                {
                    log.LogInformation("CC Recipients Added: 0");
                }

                //bcc recipients
                if (!string.IsNullOrEmpty(bccRecipients))
                {
                    var allBccRecipients = bccRecipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var bccAddress in allBccRecipients)
                    {
                        mail.Bcc.Add(bccAddress);
                    }
                    log.LogInformation("BCC Recipients Added: " + allBccRecipients.Count().ToString());
                }
                else
                {
                    log.LogInformation("BCC Recipients Added: 0");
                }
                #endregion

                #region SendEmail
                try
                {
                    log.LogInformation("Sending email.");

                    client.Send(mail);
                    outputString = "{ \"EmailSent\": true }";

                    log.LogInformation("Sent email.");
                }
                catch (SmtpException smtpEx)
                {
                    outputString = "{ \"EmailSent\": false, \"Details\": \"SMTP exception caught and logged to error output.\"}";

                    log.LogError(smtpEx.Message);
                    log.LogInformation("Message has not been sent. Check Azure Function Logs for more information.");
                }
                catch (Exception ex)
                {
                    outputString = "{ \"EmailSent\": false, \"Details\": \"Other exception caught and logged to error output.\"}";

                    log.LogError(ex.Message);
                    log.LogInformation("Message has not been sent. Check Azure Function Logs for more information.");
                }
                #endregion
            }

            outputJson = JObject.Parse(outputString);

            log.LogInformation("SendEmail Function complete.");
            return(new OkObjectResult(outputJson));
        }
Пример #22
0
 public SenderEmailRepository(SMTPClient SMTPClient)
 {
     _SMTPClient = SMTPClient;
 }
Пример #23
0
 public static Task <MailSentStatus> SendVia(this EMail EMail,
                                             SMTPClient SMTPClient,
                                             Byte NumberOfRetries = 3)
 {
     return(SMTPClient.Send(EMail, NumberOfRetries));
 }
Пример #24
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("SendEmail Function triggered by HTTP request.");

            #region ParseRequestBody
            log.LogInformation("Parsing body from request.");

            string  requestBody  = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data         = JsonConvert.DeserializeObject(requestBody);
            string  outputString = string.Empty;

            string recipients       = data?.emailRecipients;
            string ccRecipients     = data?.emailCcRecipients;
            string subject          = data?.emailSubject;
            string message          = data?.emailBody;
            string passedImportance = data?.emailImportance ?? ""; //Assume normal importance if not provided.

            //Check for minimum values in body
            if (
                recipients == null ||
                subject == null ||
                message == null
                )
            {
                log.LogInformation("Invalid body.");
                return(new BadRequestObjectResult("Invalid request body, value(s) missing."));
            }

            #endregion

            //Create email client
            log.LogInformation("Creating smtp client.");

            using (var client = SMTPClient.CreateSMTPClient())
            {
                #region CreateMail
                MailAddress from = new MailAddress(SMTPClient.fromEmail);
                MailMessage mail = new MailMessage
                {
                    From       = from,
                    IsBodyHtml = true,
                    Subject    = subject,
                    Body       = message
                };

                //Set mail importance
                if (passedImportance.ToUpper() == "HIGH")
                {
                    mail.Priority = MailPriority.High;
                }
                else if (passedImportance.ToUpper() == "LOW")
                {
                    mail.Priority = MailPriority.Low;
                }
                else
                {
                    mail.Priority = MailPriority.Normal;
                }
                #endregion

                #region SetRecipients
                //recipients
                foreach (var address in recipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    mail.To.Add(address);
                }

                //cc recipients
                if (!string.IsNullOrEmpty(ccRecipients))
                {
                    foreach (var ccAddress in ccRecipients.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        mail.CC.Add(ccAddress);
                    }
                }
                #endregion

                #region SendEmail
                try
                {
                    log.LogInformation("Sending email.");

                    client.Send(mail);
                    outputString = "{ \"EmailSent\": true }";

                    log.LogInformation("Sent email.");
                }
                catch (SmtpException smtpEx)
                {
                    outputString = "{ \"EmailSent\": false }";

                    log.LogError(smtpEx.Message);
                    log.LogInformation("Message has not been sent. Check Azure Function Logs for more information.");
                }
                catch (Exception ex)
                {
                    outputString = "{ \"EmailSent\": false }";

                    log.LogError(ex.Message);
                    log.LogInformation("Message has not been sent. Check Azure Function Logs for more information.");
                }
                #endregion
            }

            JObject outputJson = JObject.Parse(outputString);

            log.LogInformation("SendEmail Function complete.");
            return(new OkObjectResult(outputJson));
        }