예제 #1
0
        private bool SendEmailViaOutlook(EmailConfiguration emailConfig)
        {
            ClientConfiguration.EmailSettings config = Program.Configuration.Email;
            bool wasSuccessful = false;

            try
            {
                //now create mail object (but we'll not send it via outlook)
                _log.Trace("Creating outlook mail item");
                dynamic mailItem = _app.CreateItem(OlItemType.olMailItem);

                //Add subject
                if (!string.IsNullOrWhiteSpace(emailConfig.Subject))
                {
                    mailItem.Subject = emailConfig.Subject;
                }

                _log.Trace($"Setting message subject to: {mailItem.Subject}");

                //Set message body according to type of message
                switch (emailConfig.BodyType)
                {
                case EmailConfiguration.EmailBodyType.HTML:
                    mailItem.HTMLBody = emailConfig.Body;
                    _log.Trace($"Setting message HTMLBody to: {emailConfig.Body}");
                    break;

                case EmailConfiguration.EmailBodyType.RTF:
                    mailItem.RTFBody = emailConfig.Body;
                    _log.Trace($"Setting message RTFBody to: {emailConfig.Body}");
                    break;

                case EmailConfiguration.EmailBodyType.PlainText:
                    mailItem.Body = emailConfig.Body;
                    _log.Trace($"Setting message Body to: {emailConfig.Body}");
                    break;

                default:
                    throw new Exception("Bad email body type: " + emailConfig.BodyType);
                }

                //attachments
                if (emailConfig.Attachments.Count > 0)
                {
                    //Add attachments
                    foreach (string path in emailConfig.Attachments)
                    {
                        mailItem.Attachments.Add(path);
                        _log.Trace($"Adding attachment from: {path}");
                    }
                }

                if (config.SetAccountFromConfig || config.SetAccountFromLocal)
                {
                    Accounts accounts = _app.Session.Accounts;
                    Account  acc      = null;

                    if (config.SetAccountFromConfig)
                    {
                        //Look for our account in the Outlook
                        foreach (Account account in accounts)
                        {
                            if (account.SmtpAddress.Equals(emailConfig.From, StringComparison.CurrentCultureIgnoreCase))
                            {
                                //Use it
                                acc = account;
                                break;
                            }
                        }
                    }

                    //TODO: if no from account found, just use first one found to send - but should ghosts do this?
                    if (acc == null)
                    {
                        foreach (Account account in accounts)
                        {
                            acc = account;
                            break;
                        }
                    }

                    //Did we get the account?
                    if (acc != null)
                    {
                        _log.Trace($"Sending via {acc.DisplayName}");
                        //Use this account to send the e-mail
                        mailItem.SendUsingAccount = acc;
                    }
                }

                if (config.SaveToOutbox)
                {
                    _log.Trace("Saving mailItem to outbox...");
                    mailItem.Move(_folderOutbox);
                    mailItem.Save();
                }

                _log.Trace("Attempting new Redemtion SafeMailItem...");
                SafeMailItem rdoMail = new Redemption.SafeMailItem
                {
                    Item = mailItem
                };
                //Parse To
                if (emailConfig.To.Count > 0)
                {
                    System.Collections.Generic.IEnumerable <string> list = emailConfig.To.Distinct();
                    foreach (string a in list)
                    {
                        SafeRecipient r = rdoMail.Recipients.AddEx(a.Trim());
                        r.Resolve();
                        _log.Trace($"RdoMail TO {a.Trim()}");
                    }
                }
                else
                {
                    throw new Exception("Must specify to-address");
                }

                //Parse Cc
                if (emailConfig.Cc.Count > 0)
                {
                    System.Collections.Generic.IEnumerable <string> list = emailConfig.Cc.Distinct();
                    foreach (string a in list)
                    {
                        SafeRecipient r = rdoMail.Recipients.AddEx(a.Trim());
                        r.Resolve();
                        if (r.Resolved)
                        {
                            r.Type = 2; //CC
                        }

                        _log.Trace($"RdoMail CC {a.Trim()}");
                    }
                }

                if (emailConfig.Bcc.Count > 0)
                {
                    System.Collections.Generic.IEnumerable <string> list = emailConfig.Bcc.Distinct();
                    foreach (string a in list)
                    {
                        SafeRecipient r = rdoMail.Recipients.AddEx(a.Trim());
                        r.Resolve();
                        if (r.Resolved)
                        {
                            r.Type = 3; //BCC
                        }

                        _log.Trace($"RdoMail BCC {a.Trim()}");
                    }
                }

                /*
                 *  outlook_mail_item = self._outlook.outlook_application.CreateItem(win32com.client.constants.olMailItem)
                 *  outlook_mail_item = outlook_mail_item.Move(outbox)
                 *
                 *  outlook_mail_item.Subject = subject
                 *  outlook_mail_item.Body = body
                 *  outlook_mail_item.Save()
                 *
                 *  for file_ in self._config['attachments']:
                 *      outlook_mail_item.Attachments.Add(file_)
                 *
                 # Need to use Redemption to actually get it to send correctly.
                 #  new_email = win32com.client.Dispatch('Redemption.SafeMailItem')
                 #  new_email.Item = outlook_mail_item
                 #  new_email.Recipients.Add(self._config['destination'])
                 #  new_email.Recipients.ResolveAll()
                 #  new_email.Send()
                 */


                rdoMail.Recipients.ResolveAll();

                _log.Trace("Attempting to send Redemtion SafeMailItem...");
                rdoMail.Send();

                var mapiUtils = new Redemption.MAPIUtils();
                mapiUtils.DeliverNow();

                //Done
                wasSuccessful = true;

                _log.Trace("Redemtion SafeMailItem was sent successfully");

                if (config.SetForcedSendReceive)
                {
                    _log.Trace("Forcing mapi - send and receive");
                    _oMapiNamespace.SendAndReceive(false);
                    Thread.Sleep(3000);
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }
            _log.Trace($"Returning - wasSuccessful:{wasSuccessful}");
            return(wasSuccessful);
        }
예제 #2
0
 public Emailer(EmailConfiguration emailConfiguration)
 {
     _emailConfiguration = emailConfiguration;
 }
예제 #3
0
 public EmailService(EmailConfiguration emailConfig)
 {
     _emailConfig = emailConfig;
 }
 public EmailManager(ITenantSettings <EmailConfiguration> emailConfiguration, IEmailFactory emailFactory, ILogger <EmailManager> logger)
 {
     _emailConfiguration = emailConfiguration.Value;
     _emailFactory       = emailFactory;
     _logger             = logger;
 }
예제 #5
0
 public AppointmentService(ApplicationDbContext db, IEmailSender emailSender, EmailConfiguration emailCongig)
 {
     _db          = db;
     _emailSender = emailSender;
     _emailConfig = emailCongig;
 }
예제 #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAWSServices(Configuration);
            services.AddAWSService <IAmazonSimpleEmailService>();

            services.AddDbContext <CipaContext>(options =>
            {
                options.UseLazyLoadingProxies();
                options.UseMySql(Configuration.GetConnectionString("MySqlConnection"),
                                 b => b.MigrationsAssembly("Cipa.WebApi"));
            });

            var signingConfigurations = new SigningConfigurations(Configuration.GetSection("TokenConfigurations:Secret").Value);

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);

            var importacaoConfiguration = new ImportacaoServiceConfiguration();

            new ConfigureFromConfigurationOptions <ImportacaoServiceConfiguration>(
                Configuration.GetSection("Importacao"))
            .Configure(importacaoConfiguration);
            services.AddSingleton <IImportacaoServiceConfiguration>(importacaoConfiguration);

            var emailConfiguration = new EmailConfiguration();

            new ConfigureFromConfigurationOptions <EmailConfiguration>(
                Configuration.GetSection("Email"))
            .Configure(emailConfiguration);
            services.AddSingleton(emailConfiguration);

            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => JwtBeareOptionsConfig.JwtConfiguration(options, signingConfigurations, tokenConfigurations));

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy(PoliticasAutorizacao.UsuarioSESMT, AuthorizationPolicies.UsuarioSESMTAuthorizationPolicy);
                auth.AddPolicy(PoliticasAutorizacao.UsuarioSESMTContaValida, AuthorizationPolicies.UsuarioSESMTPossuiContaValidaAuthorizationPolicy);
            });

            // AutoMapper
            services.AddSingleton(AutoMapperConfig.MapperConfig());

            // Dependências
            AddDependencies(services);

            services.AddCors(options => options.AddPolicy("AllowAll", builder => builder
                                                          .WithMethods("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT ")
                                                          .WithHeaders("Content-Type", "X-Amz-Date", "Authorization", "X-Api-Key", "X-Amz-Security-Token", "X-Requested-With")
                                                          .AllowCredentials()
                                                          .WithOrigins("http://localhost:4200", "https://cipa.4uptech.com.br")));

            services.AddHostedService <ImportacaoHostedService>();
            services.AddHostedService <EmailHostedService>();
            services.AddHostedService <ProcesssamentoEtapasHostedService>();
            services.AddHostedService <AlteracaoEtapaService>();

            services.Configure <GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromSeconds(63072000);
            });

            services.AddResponseCompression(options =>
            {
                IEnumerable <string> MimeTypes = new[]
                {
                    // General
                    "text/plain",
                    "text/html",
                    "text/css",
                    "font/woff2",
                    "application/javascript",
                    "image/x-icon",
                    "image/png"
                };

                options.EnableForHttps = true;
                options.MimeTypes      = MimeTypes;
                options.Providers.Add <GzipCompressionProvider>();
            });

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                loggingBuilder.AddConsole();
                loggingBuilder.AddDebug();
                loggingBuilder.AddAWSProvider(Configuration.GetAWSLoggingConfigSection());
            });
            services.AddRouting();
            services.AddSignalR();
            services.AddSingleton <IUserIdProvider, CustomUserIdProvider>();
            services.AddControllers().AddNewtonsoftJson();
        }
 public EmailNotifier(EmailConfiguration configuration)
 {
     _configuration = configuration;
     _client        = new SmtpClient(configuration.SmtpAddress, configuration.SmtpPort);
 }
예제 #8
0
 public AccountsController(AccountService service, LogService logService, EmailConfiguration emailConfiguration)
 {
     _service            = service;
     _logService         = logService;
     _emailConfiguration = emailConfiguration;
 }
예제 #9
0
 public ContactController(IOptions <EmailConfiguration> emailConfiguration)
 {
     _emailConfiguration = emailConfiguration.Value;
 }
예제 #10
0
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
        {
            // Register Infrastrucruter Services
            services.AddScoped <IUserManager, UserManagerService>();
            services.AddScoped <ISignInManager, SignInManagerService>();
            services.AddTransient <IJwtSecurityTokenManager, JwtSecurityTokenManager>();
            services.AddTransient <ISecurityTokenService, SecurityTokenService>();

            // Register FluentEmail Services
            var emailConfig = new EmailConfiguration();

            configuration.GetSection(nameof(EmailConfiguration)).Bind(emailConfig);

            services.AddFluentEmail(defaultFromEmail: emailConfig.Email)
            .AddRazorRenderer()
            .AddSmtpSender(new SmtpClient(emailConfig.Host, emailConfig.Port)
            {
                DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory,
                PickupDirectoryLocation = @"C:\Users\mgayle\email",
                //DeliveryMethod = SmtpDeliveryMethod.Network,
                //Credentials = new NetworkCredential(emailConfig.Email, emailConfig.Password),
                EnableSsl = emailConfig.EnableSsl
            });

            // Add EmailNotification Service
            services.AddScoped <IEmailNotification, EmailNotificationService>();

            // Register Identity DbContext and Server
            services.AddDbContext <ApplicationIdentityDbContext>(options =>
                                                                 options.UseSqlServer(configuration.GetConnectionString("Net5WebTemplateDbConnection")));

            var identityOptionsConfig = new IdentityOptionsConfig();

            configuration.GetSection(nameof(IdentityOptionsConfig)).Bind(identityOptionsConfig);

            services.AddDefaultIdentity <ApplicationUser>(options =>
            {
                options.Password.RequiredLength         = identityOptionsConfig.RequiredLength;
                options.Password.RequireDigit           = identityOptionsConfig.RequiredDigit;
                options.Password.RequireLowercase       = identityOptionsConfig.RequireLowercase;
                options.Password.RequiredUniqueChars    = identityOptionsConfig.RequiredUniqueChars;
                options.Password.RequireUppercase       = identityOptionsConfig.RequireUppercase;
                options.Lockout.MaxFailedAccessAttempts = identityOptionsConfig.MaxFailedAttempts;
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromDays(identityOptionsConfig.LockoutTimeSpanInDays);
            })
            .AddEntityFrameworkStores <ApplicationIdentityDbContext>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <PasswordResetTokenProvider <ApplicationUser> >("CustomPasswordReset");

            // Configure Pasword reset Token lifespan
            services.Configure <PasswordResetTokenProviderOptions>(options =>
            {
                options.TokenLifespan = TimeSpan.FromMinutes(configuration.GetValue <int>("PasswordResetToken:LifespanInMinutes"));
            });

            // Configure JWT Authentication and Authorization
            var jwtSettings = new JwtSettings();

            configuration.Bind(nameof(JwtSettings), jwtSettings);
            services.AddSingleton(jwtSettings);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = jwtSettings.ValidateIssuerSigningKey,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret)),
                ValidateIssuer           = jwtSettings.ValidateIssuer,
                ValidateAudience         = jwtSettings.ValidateAudience,
                RequireExpirationTime    = jwtSettings.RequireExpirationTime,
                ValidateLifetime         = jwtSettings.ValidateLifetime,
                ClockSkew = jwtSettings.Expiration
            };

            services.AddSingleton(tokenValidationParameters);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.SaveToken = true;
                options.TokenValidationParameters = tokenValidationParameters;
            });

            return(services);
        }
예제 #11
0
 public EmailService(EmailConfiguration configuration, ILogger logger)
 {
     this.logger = logger;
     InitializerClient(configuration);
     sender = configuration.SenderEmail;
 }
예제 #12
0
 public EmailService(IConfiguration configuration)
 {
     Configuration = new EmailConfiguration();
     configuration.GetSection("Email").Bind(Configuration);
 }
예제 #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // services.AddTransient<AuthRepository>();
            services.AddTransient <KatalogRepository>();
            services.AddTransient <ProductRepository>();
            services.AddTransient <ImageRepository>();
            services.AddTransient <TypeProductRepository>();
            services.AddTransient <ProductItemRepository>();
            services.AddTransient <ITokenService, TokenService>();

            services.AddAutoMapper(typeof(Startup)); //18.11.21

            int _potr       = int.TryParse(Environment.GetEnvironmentVariable("Port"), out _potr) ? _potr : 465;
            var emailConfig = new EmailConfiguration
            {
                From       = Environment.GetEnvironmentVariable("From"),
                SmtpServer = Environment.GetEnvironmentVariable("SmtpServer"),
                Port       = _potr,
                Password   = Environment.GetEnvironmentVariable("Password"),
                UserName   = Environment.GetEnvironmentVariable("UserName")
            };

            services.AddSingleton <IEmailSender> (new EmailSender(emailConfig)); //23.11.21



            services.AddControllers();

            services.AddCors(
                option => option.AddDefaultPolicy(builder => builder
                                                  .WithOrigins(Environment.GetEnvironmentVariable("FrontClient"))
                                                  // .AllowAnyOrigin()
                                                  .AllowAnyHeader()
                                                  .AllowAnyMethod()
                                                  .AllowCredentials()

                                                  ));

            //   var authConfig = Configuration.GetSection("Auth");
            var connectStringShop        = Environment.GetEnvironmentVariable("ConnectString") + "database=ShopDB;";
            var connectStringAppIdentity = Environment.GetEnvironmentVariable("ConnectString") + "database=AppIdentityDB;";

            //  var serverVersion = new MySqlServerVersion(new Version(8, 0,21));

            // Replace 'YourDbContext' with the name of your own DbContext derived class.
            services.AddDbContext <MyShopContext>(
                options => options
                .UseMySql(connectStringShop, new MySqlServerVersion(new Version(8, 0, 11)))

                );

            services.AddDbContext <AppIdentityDbContext>(
                options => options.UseMySql(connectStringAppIdentity, new MySqlServerVersion(new Version(8, 0, 11))
                                            ));

            // затем подключаем сервисы Identity
            services.AddIdentity <User, IdentityRole> ()
            .AddEntityFrameworkStores <AppIdentityDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <DataProtectionTokenProviderOptions>(opt =>
                                                                    opt.TokenLifespan = TimeSpan.FromHours(2));


            services.AddAuthentication(
                opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }
                )
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // укзывает, будет ли валидироваться издатель при валидации токена
                    ValidateIssuer = true,
                    // строка, представляющая издателя
                    ValidIssuer = Environment.GetEnvironmentVariable("Issuer"),

                    // будет ли валидироваться потребитель токена
                    ValidateAudience = true,
                    // установка потребителя токена
                    ValidAudience = Environment.GetEnvironmentVariable("Audience"),
                    // будет ли валидироваться время существования
                    ValidateLifetime = true,

                    // установка ключа безопасности
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("ClientSecrets"))),
                    // валидация ключа безопасности
                    ValidateIssuerSigningKey = true
                };

                //----------------------------------
            });
        }
예제 #14
0
 public EmailSender(EmailConfiguration emailConfig)
 {
     _emailConfig = emailConfig;
 }
예제 #15
0
        public void ExecuteEvents(TimelineHandler handler)
        {
            try
            {
                foreach (var timelineEvent in handler.TimeLineEvents)
                {
                    WorkingHours.Is(handler);

                    if (timelineEvent.DelayBefore > 0)
                    {
                        Thread.Sleep(timelineEvent.DelayBefore);
                    }

                    switch (timelineEvent.Command.ToUpper())
                    {
                    default:
                        try
                        {
                            var emailConfig = new EmailConfiguration(timelineEvent.CommandArgs);
                            if (SendEmailViaOutlook(emailConfig))
                            {
                                Report(handler.HandlerType.ToString(), timelineEvent.Command, emailConfig.ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }

                        break;

                    case "REPLY":
                        try
                        {
                            EmailConfiguration emailConfig = new EmailConfiguration(timelineEvent.CommandArgs);
                            if (ReplyViaOutlook(emailConfig))
                            {
                                Report(handler.HandlerType.ToString(), timelineEvent.Command, emailConfig.ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }
                        break;

                    case "NAVIGATE":
                        try
                        {
                            if (Navigate(timelineEvent.CommandArgs))
                            {
                                Report(handler.HandlerType.ToString(), timelineEvent.Command, string.Join(",", timelineEvent.CommandArgs));
                            }
                        }
                        catch (Exception e)
                        {
                            _log.Error(e);
                        }
                        break;
                    }

                    if (timelineEvent.DelayAfter > 0)
                    {
                        Thread.Sleep(timelineEvent.DelayAfter);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Debug(e);
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        int page = 1;

        if (Request.QueryString["page"] == null)
        {
            Response.Redirect("ImapClientProtocolUnseen.aspx?page=1");
            Response.Flush();
            Response.End();
        }
        else
        {
            page = Convert.ToInt32(Request.QueryString["page"]);
        }
        try
        {
            Email    = Session["email"].ToString();
            Password = Session["pwd"].ToString();

            int totalEmails;
            //List<EMail> emails;
            string             emailAddress;
            EmailConfiguration email = new EmailConfiguration();
            email.IMAPServer   = "imap.gmail.com"; // type your popserver
            email.IMAPUsername = Email;            // type your username credential
            email.IMAPpassword = Password;         // type your password credential
            email.IncomingPort = "993";
            email.IsIMAPssl    = true;
            int success = 0;
            //int fail = 0;

            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            ImapClient ic = new ImapClient(email.IMAPServer, email.IMAPUsername, email.IMAPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsIMAPssl);
            ic.SelectMailbox("INBOX");
            uids = ic.Search("UNSEEN");
            int co = uids.Count();
            totalEmails = ic.GetMessageCount();

            emailAddress = Email;


            int totalPages;
            int mod = (co) % NoOfEmailsPerPage;
            if (mod == 0)
            {
                totalPages = (co) / NoOfEmailsPerPage;
            }
            else
            {
                totalPages = ((co - mod) / NoOfEmailsPerPage) + 1;
            }

            int i = 0;
            foreach (var uid in uids)
            {
                MailMessege obj     = new MailMessege();
                var         message = ic.GetMessage(uid);
                obj.sender   = message.From.ToString();
                obj.sendDate = message.Date;
                obj.subject  = message.Subject;
                obj.UID      = message.Uid; //UID is unique identifier assigned to each message by mail server
                if (message.Attachments == null)
                {
                }
                else
                {
                    obj.Attachments = message.Attachments;
                }
                //model.Inbox.Add(obj);
                success++;
                int       emailId = ((page - 1) * NoOfEmailsPerPage) + i + 1;
                TableCell noCell  = new TableCell();
                noCell.CssClass = "emails-table-cell";
                noCell.Text     = Convert.ToString(emailId);
                TableCell fromCell = new TableCell();
                fromCell.CssClass = "emails-table-cell";
                fromCell.Text     = obj.sender;

                TableCell subjectCell = new TableCell();
                subjectCell.CssClass       = "emails-table-cell";
                subjectCell.Style["width"] = "300px";
                subjectCell.Text           = String.Format(DisplayEmailLink, emailId, obj.subject);
                TableCell dateCell = new TableCell();
                dateCell.CssClass = "emails-table-cell";
                if (obj.sendDate != DateTime.MinValue)
                {
                    dateCell.Text = obj.sendDate.ToString();
                }
                TableRow emailRow = new TableRow();
                emailRow.Cells.Add(noCell);
                emailRow.Cells.Add(fromCell);
                emailRow.Cells.Add(subjectCell);
                emailRow.Cells.Add(dateCell);
                EmailsTable.Rows.AddAt(2 + i, emailRow);
                i = i + 1;
            }

            if (totalPages > 1)
            {
                if (page > 1)
                {
                    PreviousPageLiteral.Text = String.Format(SelfLink, page - 1, "Previous Page");
                }
                if (page > 0 && page < totalPages)
                {
                    NextPageLiteral.Text = String.Format(SelfLink, page + 1, "Next Page");
                }
            }
            EmailFromLiteral.Text  = Convert.ToString(((page - 1) * NoOfEmailsPerPage) + 1);
            EmailToLiteral.Text    = Convert.ToString(page * NoOfEmailsPerPage);
            EmailTotalLiteral.Text = Convert.ToString(totalEmails);
            EmailLiteral.Text      = emailAddress;
        }catch (Exception ex)

        {
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Error';", true);
        }
    }
예제 #17
0
 public async Task<IHttpActionResult> SendMail()
 {
     try
     {
         EmailConfiguration configuration = new EmailConfiguration();
         var smtp = new System.Net.Mail.SmtpClient();
         {
             smtp.Host = configuration.SmtpHost;//"smtp.gmail.com";
             smtp.Port = configuration.SmtpPort;
             smtp.EnableSsl = configuration.EnableSsl;
             smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
             smtp.Credentials = new NetworkCredential(configuration.FromAddress, configuration.FromPassword);
             smtp.Timeout = 20000;
         }
         smtp.Send(configuration.FromAddress, toAddress, configuration.Subject, body);
         return true;
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message, ex);
         return false;
     }
 }
예제 #18
0
 public SmtpEmailSender(EmailConfiguration config)
 {
     _config = config;
 }