/// <inheritdoc />
        public MimeMessage CreateFromMessageWithAttachment(string fromAddress, string toAddress, IEnumerable <string> cc, string subject, byte[] fileContent,
                                                           string fileName, string bodyHtml, string templateName = "")
        {
            //Validate inputs
            if (string.IsNullOrEmpty(fromAddress))
            {
                throw new ArgumentNullException(nameof(fromAddress));
            }
            if (string.IsNullOrEmpty(toAddress))
            {
                throw new ArgumentNullException(nameof(toAddress));
            }
            if (string.IsNullOrEmpty(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }
            if (fileContent == null)
            {
                throw new ArgumentNullException(nameof(fileContent));
            }
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (string.IsNullOrEmpty(bodyHtml))
            {
                throw new ArgumentNullException(nameof(bodyHtml));
            }

            //Convert
            var toSend = new MimeMessage();

            toSend.From.Add(MailboxAddress.Parse(fromAddress));
            toSend.To.Add(MailboxAddress.Parse(toAddress));

            if (_serviceOptions.AddEnvironmentSuffix && !_hostingEnvironment.IsProduction())
            {
                toSend.Subject = $"{subject} ({_hostingEnvironment.EnvironmentName})";
            }
            else
            {
                toSend.Subject = subject;
            }

            //Add CC's if needed
            if (cc != null)
            {
                foreach (var item in cc)
                {
                    try
                    {
                        toSend.Cc.Add(MailboxAddress.Parse(item));
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, $"Unable to add {item} to email copy list");
                    }
                }
            }

            //Perform templating
            if (_serviceOptions.AlwaysTemplateEmails && string.IsNullOrEmpty(templateName))
            {
                bodyHtml = _emailTemplateFactory.BuildEmailContent(toSend.Subject, bodyHtml);
            }
            else if (!string.IsNullOrEmpty(templateName))
            {
                bodyHtml = _emailTemplateFactory.BuildEmailContent(toSend.Subject, bodyHtml,
                                                                   templateName: templateName);
            }

            var bodyBuilder = new BodyBuilder {
                HtmlBody = bodyHtml
            };

            bodyBuilder.Attachments.Add(fileName, fileContent);
            toSend.Body = bodyBuilder.ToMessageBody();
            return(toSend);
        }
Beispiel #2
0
        private static void Proccess(List <AttLog> attlogs, string location, bool mode, string connectString, string linkChamCong, bool modeEmail)
        {
            #region Connection
            MongoDBContext.ConnectionString = connectString;
            MongoDBContext.DatabaseName     = "tribat";
            MongoDBContext.IsSSL            = true;
            MongoDBContext dbContext = new MongoDBContext();
            #endregion

            #region Config
            var    dateNewPolicy       = new DateTime(2018, 10, 01);
            double workingScheduleHour = 8;
            var    lunch = TimeSpan.FromHours(1);

            #endregion

            var groups = (from p in attlogs
                          group p by new
            {
                p.EnrollNumber,
                p.Date.Date
            }
                          into d
                          select new
            {
                groupDate = d.Key.Date.ToString("yyyy-MM-dd"),
                groupCode = d.Key.EnrollNumber,
                count = d.Count(),
                times = d.ToList(),
            }).ToList();

            foreach (var group in groups)
            {
                Console.WriteLine("Date: " + group.groupDate + ", fingerCode: " + group.groupCode + ", location: " + location);
                try
                {
                    var    dateData = DateTime.ParseExact(group.groupDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    var    workTime = new TimeSpan(0);
                    double workDay  = 1;
                    var    late     = new TimeSpan(0);
                    var    early    = new TimeSpan(0);
                    // 0: cần xác nhận công; 1: đủ ngày công ; 2: đã gửi xác nhận công, 3: đồng ý; 4: từ chối
                    var status      = 1;
                    var statusLate  = 1;
                    var statusEarly = 1;

                    var linkFinger   = string.Empty;
                    var enrollNumber = group.groupCode;
                    var records      = group.times.OrderBy(m => m.Date).ToList();
                    var dateFinger   = records.First().DateOnlyRecord;
                    var inLogTime    = records.First().TimeOnlyRecord;
                    var outLogTime   = records.Last().TimeOnlyRecord;

                    #region Save to db: In/Out log
                    TimeSpan?dbinLogTime  = inLogTime;
                    TimeSpan?dboutLogTime = outLogTime;
                    #endregion

                    #region Define working hour schedule & email send notice
                    var employeeId = string.Empty;
                    var email      = string.Empty;
                    var fullName   = string.Empty;
                    var title      = string.Empty;
                    var startWorkingScheduleTime = TimeSpan.FromHours(8);
                    var endWorkingScheduleTime   = TimeSpan.FromHours(17);
                    var filterEmp = Builders <Employee> .Filter.ElemMatch(z => z.Workplaces, a => a.Fingerprint == enrollNumber);

                    var employee = dbContext.Employees.Find(filterEmp).FirstOrDefault();
                    if (employee != null)
                    {
                        employeeId = employee.Id;
                        var workplaces = employee.Workplaces;
                        if (workplaces != null && workplaces.Count > 0)
                        {
                            foreach (var workplace in employee.Workplaces)
                            {
                                if (!string.IsNullOrEmpty(workplace.Fingerprint) && workplace.Fingerprint == enrollNumber)
                                {
                                    startWorkingScheduleTime = TimeSpan.Parse(workplace.WorkingScheduleTime.Split('-')[0].Trim());
                                    endWorkingScheduleTime   = TimeSpan.Parse(workplace.WorkingScheduleTime.Split('-')[1].Trim());
                                }
                            }
                        }
                        email      = employee.Email;
                        fullName   = employee.FullName;
                        title      = employee.Title;
                        linkFinger = linkChamCong + employee.Id;
                    }
                    #endregion

                    #region Procees Times
                    // No Data
                    if (!dbinLogTime.HasValue && !dboutLogTime.HasValue)
                    {
                        workTime = new TimeSpan(0);
                        workDay  = 0;
                        status   = 0;
                    }
                    else
                    {
                        if (group.times != null && group.times.Count > 1)
                        {
                            if (dateFinger < dateNewPolicy)
                            {
                                status      = 1;
                                statusEarly = 1;
                                statusLate  = 1;
                                workDay     = 1;
                                workTime    = TimeSpan.FromHours(8);
                            }
                            else
                            {
                                // Rule: If the start time is before the starting hours, set it to the starting hour.
                                // New Rule:
                                // ** Nếu không được xác nhận công:
                                //  - Trễ 15 phút không tính buổi nào không tính buổi đó. (1 buổi tương đương 0.5 ngày)
                                //  - Trễ  dưới 15 phút lưu để trừ thưởng,...
                                if (inLogTime < startWorkingScheduleTime)
                                {
                                    inLogTime = startWorkingScheduleTime;
                                }
                                if (outLogTime > endWorkingScheduleTime)
                                {
                                    outLogTime = endWorkingScheduleTime;
                                }

                                workTime = (outLogTime - inLogTime) - lunch;
                                //workDay = workTime.TotalHours / workingScheduleHour;

                                if (inLogTime > startWorkingScheduleTime)
                                {
                                    late       = inLogTime - startWorkingScheduleTime;
                                    statusLate = 0;
                                    status     = 0;
                                    //workDay = workDay - 0.5;
                                }
                                if (outLogTime < endWorkingScheduleTime)
                                {
                                    early       = endWorkingScheduleTime - outLogTime;
                                    statusEarly = 0;
                                    status      = 0;
                                    //workDay = workDay - 0.5;
                                }
                            }
                        }
                        else
                        {
                            // Check miss in/out
                            var workingArr = new int[] { startWorkingScheduleTime.Hours, endWorkingScheduleTime.Hours };
                            var incheck    = workingArr.ClosestTo(dbinLogTime.Value.Hours);
                            var outcheck   = workingArr.ClosestTo(dboutLogTime.Value.Hours);
                            if (incheck == outcheck)
                            {
                                if (incheck == endWorkingScheduleTime.Hours)
                                {
                                    // missing in
                                    dbinLogTime = null;
                                    late        = new TimeSpan(0);
                                    early       = endWorkingScheduleTime - outLogTime;
                                    workTime    = TimeSpan.FromHours(4) - early;
                                    statusLate  = 0;
                                }
                                else
                                {
                                    // missing out
                                    dboutLogTime = null;
                                    early        = new TimeSpan(0);
                                    late         = inLogTime - startWorkingScheduleTime;
                                    workTime     = TimeSpan.FromHours(4) - late;
                                    statusEarly  = 0;
                                }
                                status  = 0;
                                workDay = 0.5;
                                //workDay = workTime.TotalHours / workingScheduleHour;
                            }
                            if (dateFinger < dateNewPolicy)
                            {
                                status      = 1;
                                statusEarly = 1;
                                statusLate  = 1;
                                workDay     = 0.5;
                                workTime    = TimeSpan.FromHours(4);
                            }
                        }
                    }

                    var employeeWorkTimeLog = new EmployeeWorkTimeLog
                    {
                        EmployeeId    = employeeId,
                        EmployeeName  = fullName,
                        EmployeeTitle = title,
                        EnrollNumber  = enrollNumber,
                        VerifyMode    = records[0].VerifyMode,
                        InOutMode     = records[0].InOutMode,
                        Workcode      = records[0].Workcode,
                        WorkplaceCode = location,
                        Date          = dateFinger,
                        In            = dbinLogTime,
                        Out           = dboutLogTime,
                        Start         = startWorkingScheduleTime,
                        End           = endWorkingScheduleTime,
                        WorkTime      = workTime,
                        WorkDay       = workDay,
                        Late          = late,
                        Early         = early,
                        Status        = status,
                        StatusLate    = statusLate,
                        StatusEarly   = statusEarly,
                        Logs          = records
                    };

                    #region DB
                    // mode = true: Get all data
                    // mode = false: get by date
                    if (mode)
                    {
                        dbContext.EmployeeWorkTimeLogs.InsertOne(employeeWorkTimeLog);
                        Console.WriteLine("Insert db: EnrollNumber: " + employeeWorkTimeLog.EnrollNumber + ", date" + employeeWorkTimeLog.Date + ", status : " + employeeWorkTimeLog.Status);
                        UpdateSummary(dbContext, dateData, employeeWorkTimeLog);
                    }
                    else
                    {
                        var employeeWorkTimeLogDb = dbContext.EmployeeWorkTimeLogs.Find(m => m.EnrollNumber.Equals(employeeWorkTimeLog.EnrollNumber) &&
                                                                                        m.Date.Equals(employeeWorkTimeLog.Date)).FirstOrDefault();
                        if (employeeWorkTimeLogDb == null)
                        {
                            dbContext.EmployeeWorkTimeLogs.InsertOne(employeeWorkTimeLog);
                            Console.WriteLine("Insert db: EnrollNumber: " + employeeWorkTimeLog.EnrollNumber + ", date" + employeeWorkTimeLog.Date + ", status : " + employeeWorkTimeLog.Status);
                            UpdateSummary(dbContext, dateData, employeeWorkTimeLog);
                        }
                        else
                        {
                            if (employeeWorkTimeLogDb.Status == 0)
                            {
                                var currentWorkTime = employeeWorkTimeLogDb.WorkTime.TotalMilliseconds;
                                var currentLate     = employeeWorkTimeLogDb.Late.TotalMilliseconds;
                                var currentEarly    = employeeWorkTimeLogDb.Early.TotalMilliseconds;
                                var currentWorkDay  = employeeWorkTimeLogDb.WorkDay;

                                var builderUpdate = Builders <EmployeeWorkTimeLog> .Filter;
                                var filterUpdate  = builderUpdate.Eq(m => m.Id, employeeWorkTimeLogDb.Id);
                                var update        = Builders <EmployeeWorkTimeLog> .Update
                                                    .Set(m => m.In, employeeWorkTimeLog.In)
                                                    .Set(m => m.Out, employeeWorkTimeLog.Out)
                                                    .Set(m => m.WorkTime, employeeWorkTimeLog.WorkTime)
                                                    .Set(m => m.WorkDay, employeeWorkTimeLog.WorkDay)
                                                    .Set(m => m.Late, employeeWorkTimeLog.Late)
                                                    .Set(m => m.Early, employeeWorkTimeLog.Early)
                                                    .Set(m => m.Status, employeeWorkTimeLog.Status)
                                                    .Set(m => m.Logs, employeeWorkTimeLog.Logs)
                                                    .Set(m => m.UpdatedOn, DateTime.Now);

                                dbContext.EmployeeWorkTimeLogs.UpdateOne(filterUpdate, update);

                                UpdateSummaryChangeData(dbContext, dateData, employeeWorkTimeLog, currentWorkTime, currentLate, currentEarly, currentWorkDay);
                            }
                        }
                    }

                    #endregion

                    #endregion

                    #region Send Mail
                    if (modeEmail)
                    {
                        if (status == 0 && dateData == DateTime.Now.Date.AddDays(-1) && !string.IsNullOrEmpty(email))
                        {
                            email = "*****@*****.**";
                            Console.WriteLine("Sending mail...");
                            var tos = new List <EmailAddress>
                            {
                                new EmailAddress {
                                    Name = fullName, Address = email
                                }
                            };
                            var webRoot     = Environment.CurrentDirectory;
                            var pathToFile  = Environment.CurrentDirectory + "/Templates/TimeKeeperNotice.html";
                            var subject     = "Xác nhận thời gian làm việc.";
                            var bodyBuilder = new BodyBuilder();
                            using (StreamReader SourceReader = File.OpenText(pathToFile))
                            {
                                bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
                            }
                            #region parameters
                            //{0} : Subject
                            //{1} : FullName
                            //{2} : EnrollNumber
                            //{3} : Workplace
                            //{4} : WorkingScheduleTime
                            //{5} : Date
                            //{6} : In
                            //{7} : Out
                            //{8} : Late
                            //{9} : Early
                            //{10}: workTime
                            //{11}: workDay
                            //{12}: logs
                            //{13}: callbackLink
                            //{14}: Website
                            //{15}: link forgot password => use login
                            //{16}: ConfirmBeforeDate
                            #endregion
                            var    url         = Constants.System.domain;
                            var    forgot      = url + Constants.System.login;
                            string messageBody = string.Format(bodyBuilder.HtmlBody,
                                                               subject,
                                                               fullName,
                                                               employeeWorkTimeLog.EnrollNumber,
                                                               employeeWorkTimeLog.WorkplaceCode,
                                                               employeeWorkTimeLog.Start + "-" + employeeWorkTimeLog.End,
                                                               employeeWorkTimeLog.Date.ToString("dd/MM/yyyy"),
                                                               employeeWorkTimeLog.In,
                                                               employeeWorkTimeLog.Out,
                                                               employeeWorkTimeLog.Late == TimeSpan.FromHours(0) ? string.Empty : employeeWorkTimeLog.Late.ToString(),
                                                               employeeWorkTimeLog.Early == TimeSpan.FromHours(0) ? string.Empty : employeeWorkTimeLog.Early.ToString(),
                                                               employeeWorkTimeLog.WorkTime,
                                                               Math.Round(employeeWorkTimeLog.WorkDay, 2),
                                                               employeeWorkTimeLog.Logs,
                                                               linkChamCong,
                                                               url,
                                                               forgot,
                                                               DateTime.Now.AddDays(1).ToShortDateString()
                                                               );
                            var emailMessage = new EmailMessage()
                            {
                                ToAddresses = tos,
                                Subject     = subject,
                                BodyContent = messageBody
                            };

                            new AuthMessageSender().SendEmail(emailMessage);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? this.Url.Content("~/");

            // Google ReCaptcha
            var recaptcha = this.recaptchaService.ValidateResponse(this.Input.Token);

            if (!recaptcha.Result.Success && recaptcha.Result.Score <= 0.5)
            {
                this.ModelState.AddModelError(string.Empty, "You are possibly using fake account!");

                this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

                return(this.Page());
            }

            this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (this.ModelState.IsValid)
            {
                var user = new User
                {
                    FirstName = this.Input.FirstName,
                    LastName  = this.Input.LastName,
                    UserName  = this.Input.Username,
                    Email     = this.Input.Email,
                    Birthdate = this.Input.Birthdate,
                };

                var result = await this.userManager.CreateAsync(user, this.Input.Password);

                if (result.Succeeded)
                {
                    this.logger.LogInformation("User created a new account with password.");

                    await this.userManager.AddToRoleAsync(user, ViewerRoleName);

                    var code = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                    var callbackUrl = this.Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: this.Request.Scheme);

                    #region Use HTML Email Template

                    var webRoot = this.env.WebRootPath;

                    // Get wwwroot Folder
                    var pathToFile = env.WebRootPath
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "templates"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "registerConfirmation.html";

                    var builder = new BodyBuilder();
                    using (StreamReader sourceReader = System.IO.File.OpenText(pathToFile))
                    {
                        builder.HtmlBody = sourceReader.ReadToEnd();
                    }

                    // {0} : callbackURL
                    var    body        = builder.HtmlBody;
                    string messageBody = string.Format(
                        builder.HtmlBody,
                        callbackUrl);

                    #endregion

                    await this.emailSender.SendEmailAsync(
                        "*****@*****.**",
                        "DotNetDari",
                        this.Input.Email,
                        "Confirm your email, bah mu 4udoto i neveroqtnata tehnologiq",
                        messageBody

                        // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."
                        );

                    if (this.userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(this.RedirectToPage("RegisterConfirmation", new { email = this.Input.Email }));
                    }
                    else
                    {
                        await this.signInManager.SignInAsync(user, isPersistent : false);

                        return(this.LocalRedirect(returnUrl));
                    }
                }

                foreach (var error in result.Errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
Beispiel #4
0
        public async Task Send(string subject, string content, MessagePriority priority)
        {
            if (Enabled)
            {
                using var client = new SmtpClient();
                try
                {
                    var options = SecureSocketOptions.None;
                    if (_secure)
                    {
                        if (_secureMode.HasValue)
                        {
                            switch (_secureMode.Value)
                            {
                            case 1:
                                options = SecureSocketOptions.Auto;
                                break;

                            case 2:
                                options = SecureSocketOptions.SslOnConnect;
                                break;

                            case 3:
                                options = SecureSocketOptions.StartTls;
                                break;

                            case 4:
                                options = SecureSocketOptions.StartTlsWhenAvailable;
                                break;
                            }
                        }
                        else
                        {
                            options = SecureSocketOptions.StartTls;
                        }
                    }
                    await client.ConnectAsync(_server, _port, options);

                    if (!string.IsNullOrEmpty(_user))
                    {
                        await client.AuthenticateAsync(new NetworkCredential(_user, _password));
                    }
                    foreach (var receiverAddress in _receiverAddresses)
                    {
                        _log.Information("Sending e-mail with subject {subject} to {_receiverAddress}", subject, receiverAddress);
                        var sender   = new MailboxAddress(_senderName, _senderAddress);
                        var receiver = new MailboxAddress(receiverAddress);
                        var message  = new MimeMessage()
                        {
                            Sender   = sender,
                            Priority = priority,
                            Subject  = subject
                        };
                        message.Subject = $"{subject} ({_computerName})";
                        message.From.Add(sender);
                        message.To.Add(receiver);
                        var bodyBuilder = new BodyBuilder();
                        bodyBuilder.HtmlBody = content + $"<p>Sent by win-acme version {_version} from {_computerName}</p>";
                        message.Body         = bodyBuilder.ToMessageBody();
                        await client.SendAsync(message);
                    }
                    await client.DisconnectAsync(true);
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Problem sending e-mail");
                }
                finally
                {
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// This will load up the Email template and generate the HTML
        /// </summary>
        /// <param name="model"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public async Task SendAdHoc(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                var email = new EmailBasicTemplate();

                var customization = await CustomizationSettings.GetSettingsAsync();

                var html = email.LoadTemplate(model.Subject, model.Message, null, customization.Logo);

                var messageId = MimeUtils.GenerateMessageId();
                if (customization.ApplicationUrl.HasValue())
                {
                    if (Uri.TryCreate(customization.ApplicationUrl, UriKind.RelativeOrAbsolute, out var url))
                    {
                        messageId = MimeUtils.GenerateMessageId(url.IdnHost);
                    }
                }

                var textBody = string.Empty;

                model.Other.TryGetValue("PlainTextBody", out textBody);
                var body = new BodyBuilder
                {
                    HtmlBody = html,
                    TextBody = textBody
                };

                var message = new MimeMessage
                {
                    Body      = body.ToMessageBody(),
                    Subject   = model.Subject,
                    MessageId = messageId
                };
                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                if (model.To.HasValue())
                {
                    message.To.Add(new MailboxAddress(model.To, model.To));
                }

                // Check for BCC
                if (model.Other.TryGetValue("bcc", out var bcc))
                {
                    var bccList = bcc.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var item in bccList)
                    {
                        message.Bcc.Add(new MailboxAddress(item, item));
                    }
                }

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        // Disable validation of the certificate associated with the SMTP service
                        // Helpful when the TLS certificate is not in the certificate store of the server
                        // Does carry the risk of man in the middle snooping
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        // Does not attempt to use either TLS or SSL
                        // Helpful when MailKit finds a TLS certificate, but it unable to use it
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    _log.LogDebug("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception when attempting to send an email");
                throw;
            }
        }
Beispiel #6
0
        public async Task Send(int userId, string subject, string body, string htmlBody = null)
        {
            var user = await _userRepository.GetByIdAsync(userId);

            var site = await _siteRepository.GetByIdAsync(user.SiteId);

            var message = new MimeMessage();

            if (!CanSendMailTo(site))
            {
                throw new GraException("Sending email is not configured.");
            }

            message.From.Add(new MailboxAddress(site.FromEmailName, site.FromEmailAddress));

            if (!string.IsNullOrWhiteSpace(_config[ConfigurationKey.EmailOverride]))
            {
                message.To.Add(new MailboxAddress(_config[ConfigurationKey.EmailOverride]));
            }
            else
            {
                message.To.Add(new MailboxAddress(user.FullName, user.Email));
            }
            message.Subject = subject;

            var builder = new BodyBuilder();

            builder.TextBody = body;
            if (!string.IsNullOrWhiteSpace(htmlBody))
            {
                builder.HtmlBody = htmlBody;
            }
            message.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                // accept any STARTTLS certificate
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                // TODO store mail server in site
                await client.ConnectAsync(site.OutgoingMailHost,
                                          site.OutgoingMailPort ?? 25,
                                          false);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                if (!string.IsNullOrEmpty(site.OutgoingMailLogin) &&
                    !string.IsNullOrEmpty(site.OutgoingMailPassword))
                {
                    client.Authenticate(site.OutgoingMailLogin, site.OutgoingMailPassword);
                }

                try
                {
                    await client.SendAsync(message);
                } catch (Exception ex)
                {
                    _logger.LogError($"Unable to send email: {ex.Message}");
                    throw new GraException("Unable to send email.", ex);
                }
                await client.DisconnectAsync(true);
            }
        }
        public IEnumerable <Instruction> Emit(BodyBuilder builder, MethodDefinition method, TraceMethod metadata)
        {
            log.Warn($"Using WriteEventCore fallback for {method}");

            var parameters = method.Parameters;
            var count      = parameters.Count;

            var data = builder.DeclareLocal(typeDefs.EventDataRef.MakePointerType());
            var item = builder.DeclareLocal(typeDefs.EventDataRef.MakePointerType());

            ////> EventData* data = stackalloc EventData[4];
            yield return(Instruction.Create(OpCodes.Ldc_I4, count));

            yield return(Instruction.Create(OpCodes.Conv_U));

            yield return(Instruction.Create(OpCodes.Sizeof, typeDefs.EventDataRef));

            yield return(Instruction.Create(OpCodes.Mul_Ovf_Un));

            yield return(Instruction.Create(OpCodes.Localloc));

            yield return(Instruction.Create(OpCodes.Stloc, data));

            ////> EventData* item = data
            yield return(Instruction.Create(OpCodes.Ldloc, data));

            yield return(Instruction.Create(OpCodes.Stloc, item));

            var first = true;

            foreach (var p in parameters)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    ////> item ++;
                    yield return(Instruction.Create(OpCodes.Ldloc, item));

                    yield return(Instruction.Create(OpCodes.Sizeof, typeDefs.EventDataRef));

                    yield return(Instruction.Create(OpCodes.Add));

                    yield return(Instruction.Create(OpCodes.Stloc, item));
                }

                ////> item->DataPointer = ...
                ////> item->Size = ...
                var emitter = emitters[ResolveFullName(p)];

                foreach (var i in emitter(builder, item, p))
                {
                    yield return(i);
                }
            }

            yield return(Instruction.Create(OpCodes.Ldarg_0));

            yield return(Instruction.Create(OpCodes.Ldc_I4, metadata.Id));

            yield return(Instruction.Create(OpCodes.Ldc_I4, count));

            yield return(Instruction.Create(OpCodes.Ldloc, data));

            yield return(Instruction.Create(OpCodes.Call, typeDefs.WriteEventCore));
        }
        private async Task SendEmail(List <MailboxAddress> userEmail, NewMessageDTO newMessageDTO, string AdTypeName, UserSendEmailAndSMS userSender)
        {
            try
            {
                string fillAttach = "";
                if (newMessageDTO.Files.Length > 0)
                {
                    fillAttach = "لقد تم ارفاق ملفات مرفقة";
                }

                var messageEmail = new MimeMessage();
                messageEmail.From.Add(new MailboxAddress("مصلحة الاحوال المدنية", "*****@*****.**"));
                messageEmail.Subject = newMessageDTO.Subject;
                var bodyBuilder = new BodyBuilder();

                messageEmail.To.AddRange(userEmail);
                //var image1 = bodyBuilder.LinkedResources.Add(@"./Img/87001570133293444.png");
                // image1.ContentId = MimeUtils.GenerateMessageId();
                bodyBuilder.HtmlBody = string.Format(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html>
<head>
    <meta charset=""UTF-8"">
    <meta content=""width=device-width, initial-scale=1"" name=""viewport"">
    <meta name=""x-apple-disable-message-reformatting"">
    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
    <meta content=""telephone=no"" name=""format-detection"">
    <title></title>
    <!--[if (mso 16)]>
    <style type=""text/css"">
    a {{text-decoration: none;}}
    </style>
    <![endif]-->
    <!--[if gte mso 9]><style>sup {{ font-size: 100% !important; }}</style><![endif]-->
    <!--[if !mso]><!-- -->
    <link href=""https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i"" rel=""stylesheet"">
    <!--<![endif]-->
    <style type=""""text/css"""">
    /* CONFIG STYLES Please do not delete and edit CSS styles below */
/* IMPORTANT THIS STYLES MUST BE ON FINAL EMAIL */
        #outlook a {{
            padding: 0;
        }}

        .ExternalClass {{
            width: 100%;
        }}

        .ExternalClass,
        .ExternalClass p,
        .ExternalClass span,
        .ExternalClass font,
        .ExternalClass td,
        .ExternalClass div {{
            line-height: 100%;
        }}

        .es-button {{
            mso-style-priority: 100 !important;
            text-decoration: none !important;
        }}

        a[x-apple-data-detectors] {{
            color: inherit !important;
            text-decoration: none !important;
            font-size: inherit !important;
            font-family: inherit !important;
            font-weight: inherit !important;
            line-height: inherit !important;
        }}

        .es-desk-hidden {{
            display: none;
            float: left;
            overflow: hidden;
            width: 0;
            max-height: 0;
            line-height: 0;
            mso-hide: all;
        }}

        /*
        END OF IMPORTANT
        */
        html,
        body {{
            width: 100%;
            font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;
            -webkit-text-size-adjust: 100%;
            -ms-text-size-adjust: 100%;
        }}

        table {{
            mso-table-lspace: 0pt;
            mso-table-rspace: 0pt;
            border-collapse: collapse;
            border-spacing: 0px;
        }}

        table td,
        html,
        body,
        .es-wrapper {{
            padding: 0;
            Margin: 0;
        }}

        .es-content,
        .es-header,
        .es-footer {{
            table-layout: fixed !important;
            width: 100%;
        }}

        img {{
            display: block;
            border: 0;
            outline: none;
            text-decoration: none;
            -ms-interpolation-mode: bicubic;
        }}

        table tr {{
            border-collapse: collapse;
        }}

        p,
        hr {{
            Margin: 0;
        }}

        h1,
        h2,
        h3,
        h4,
        h5 {{
            Margin: 0;
            line-height: 120%;
            mso-line-height-rule: exactly;
            font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;
        }}

        p,
        ul li,
        ol li,
        a {{
            -webkit-text-size-adjust: none;
            -ms-text-size-adjust: none;
            mso-line-height-rule: exactly;
        }}

        .es-left {{
            float: left;
        }}

        .es-right {{
            float: right;
        }}

        .es-p5 {{
            padding: 5px;
        }}

        .es-p5t {{
            padding-top: 5px;
        }}

        .es-p5b {{
            padding-bottom: 5px;
        }}

        .es-p5l {{
            padding-left: 5px;
        }}

        .es-p5r {{
            padding-right: 5px;
        }}

        .es-p10 {{
            padding: 10px;
        }}

        .es-p10t {{
            padding-top: 10px;
        }}

        .es-p10b {{
            padding-bottom: 10px;
        }}

        .es-p10l {{
            padding-left: 10px;
        }}

        .es-p10r {{
            padding-right: 10px;
        }}

        .es-p15 {{
            padding: 15px;
        }}

        .es-p15t {{
            padding-top: 15px;
        }}

        .es-p15b {{
            padding-bottom: 15px;
        }}

        .es-p15l {{
            padding-left: 15px;
        }}

        .es-p15r {{
            padding-right: 15px;
        }}

        .es-p20 {{
            padding: 20px;
        }}

        .es-p20t {{
            padding-top: 20px;
        }}

        .es-p20b {{
            padding-bottom: 20px;
        }}

        .es-p20l {{
            padding-left: 20px;
        }}

        .es-p20r {{
            padding-right: 20px;
        }}

        .es-p25 {{
            padding: 25px;
        }}

        .es-p25t {{
            padding-top: 25px;
        }}

        .es-p25b {{
            padding-bottom: 25px;
        }}

        .es-p25l {{
            padding-left: 25px;
        }}

        .es-p25r {{
            padding-right: 25px;
        }}

        .es-p30 {{
            padding: 30px;
        }}

        .es-p30t {{
            padding-top: 30px;
        }}

        .es-p30b {{
            padding-bottom: 30px;
        }}

        .es-p30l {{
            padding-left: 30px;
        }}

        .es-p30r {{
            padding-right: 30px;
        }}

        .es-p35 {{
            padding: 35px;
        }}

        .es-p35t {{
            padding-top: 35px;
        }}

        .es-p35b {{
            padding-bottom: 35px;
        }}

        .es-p35l {{
            padding-left: 35px;
        }}

        .es-p35r {{
            padding-right: 35px;
        }}

        .es-p40 {{
            padding: 40px;
        }}

        .es-p40t {{
            padding-top: 40px;
        }}

        .es-p40b {{
            padding-bottom: 40px;
        }}

        .es-p40l {{
            padding-left: 40px;
        }}

        .es-p40r {{
            padding-right: 40px;
        }}

        .es-menu td {{
            border: 0;
        }}

        .es-menu td a img {{
            display: inline-block !important;
        }}

        /* END CONFIG STYLES */
        a {{
            font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;
            font-size: 15px;
            text-decoration: none;
        }}

        h1 {{
            font-size: 36px;
            font-style: normal;
            font-weight: bold;
            color: #333333;
        }}

        h1 a {{
            font-size: 36px;
            text-align: left;
        }}

        h2 {{
            font-size: 30px;
            font-style: normal;
            font-weight: bold;
            color: #333333;
        }}

        h2 a {{
            font-size: 30px;
            text-align: left;
        }}

        h3 {{
            font-size: 18px;
            font-style: normal;
            font-weight: bold;
            color: #333333;
        }}

        h3 a {{
            font-size: 18px;
            text-align: left;
        }}

        p,
        ul li,
        ol li {{
            font-size: 15px;
            font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;
            line-height: 150%;
        }}

        ul li,
        ol li {{
            Margin-bottom: 15px;
        }}

        .es-menu td a {{
            text-decoration: none;
            display: block;
        }}

        .es-wrapper {{
            width: 100%;
            height: 100%;
            background-image: ;
            background-repeat: repeat;
            background-position: center top;
        }}

        .es-wrapper-color {{
            background-color: #eeeeee;
        }}

        .es-content-body {{
            background-color: #ffffff;
        }}

        .es-content-body p,
        .es-content-body ul li,
        .es-content-body ol li {{
            color: #333333;
        }}

        .es-content-body a {{
            color: #ed8e20;
        }}

        .es-header {{
            background-color: transparent;
            background-image: ;
            background-repeat: repeat;
            background-position: center top;
        }}

        .es-header-body {{
            background-color: #044767;
        }}

        .es-header-body p,
        .es-header-body ul li,
        .es-header-body ol li {{
            color: #ffffff;
            font-size: 14px;
        }}

        .es-header-body a {{
            color: #ffffff;
            font-size: 14px;
        }}

        .es-footer {{
            background-color: transparent;
            background-image: ;
            background-repeat: repeat;
            background-position: center top;
        }}

        .es-footer-body {{
            background-color: #ffffff;
        }}

        .es-footer-body p,
        .es-footer-body ul li,
        .es-footer-body ol li {{
            color: #333333;
            font-size: 14px;
        }}

        .es-footer-body a {{
            color: #333333;
            font-size: 14px;
        }}

        .es-infoblock,
        .es-infoblock p,
        .es-infoblock ul li,
        .es-infoblock ol li {{
            line-height: 120%;
            font-size: 12px;
            color: #cccccc;
        }}

        .es-infoblock a {{
            font-size: 12px;
            color: #cccccc;
        }}

        a.es-button {{
            border-style: solid;
            border-color: #ed8e20;
            border-width: 15px 30px 15px 30px;
            display: inline-block;
            background: #ed8e20;
            border-radius: 5px;
            font-size: 16px;
            font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;
            font-weight: bold;
            font-style: normal;
            line-height: 120%;
            color: #ffffff;
            text-decoration: none;
            width: auto;
            text-align: center;
        }}

        .es-button-border {{
            border-style: solid solid solid solid;
            border-color: transparent transparent transparent transparent;
            background: #ed8e20;
            border-width: 0px 0px 0px 0px;
            display: inline-block;
            border-radius: 5px;
            width: auto;
        }}

        /* RESPONSIVE STYLES Please do not delete and edit CSS styles below. If you don't need responsive layout, please delete this section. */
        @media only screen and (max-width: 600px) {{

            p,
            ul li,
            ol li,
            a {{
                font-size: 16px !important;
                line-height: 150% !important;
            }}

            h1 {{
                font-size: 32px !important;
                text-align: left;
                line-height: 120% !important;
            }}

            h2 {{
                font-size: 26px !important;
                text-align: left;
                line-height: 120% !important;
            }}

            h3 {{
                font-size: 20px !important;
                text-align: left;
                line-height: 120% !important;
            }}

            h1 a {{
                font-size: 36px !important;
                text-align: left;
            }}

            h2 a {{
                font-size: 30px !important;
                text-align: left;
            }}

            h3 a {{
                font-size: 18px !important;
                text-align: left;
            }}

            .es-menu td a {{
                font-size: 16px !important;
            }}

            .es-header-body p,
            .es-header-body ul li,
            .es-header-body ol li,
            .es-header-body a {{
                font-size: 16px !important;
            }}

            .es-footer-body p,
            .es-footer-body ul li,
            .es-footer-body ol li,
            .es-footer-body a {{
                font-size: 16px !important;
            }}

            .es-infoblock p,
            .es-infoblock ul li,
            .es-infoblock ol li,
            .es-infoblock a {{
                font-size: 12px !important;
            }}

            *[class=""gmail-fix""] {{
                display: none !important;
            }}

            .es-m-txt-c,
            .es-m-txt-c h1,
            .es-m-txt-c h2,
            .es-m-txt-c h3 {{
                text-align: center !important;
            }}

            .es-m-txt-r,
            .es-m-txt-r h1,
            .es-m-txt-r h2,
            .es-m-txt-r h3 {{
                text-align: right !important;
            }}

            .es-m-txt-l,
            .es-m-txt-l h1,
            .es-m-txt-l h2,
            .es-m-txt-l h3 {{
                text-align: left !important;
            }}

            .es-m-txt-r img,
            .es-m-txt-c img,
            .es-m-txt-l img {{
                display: inline !important;
            }}

            .es-button-border {{
                display: inline-block !important;
            }}

            a.es-button {{
                font-size: 16px !important;
                display: inline-block !important;
                border-width: 15px 30px 15px 30px !important;
            }}

            .es-btn-fw {{
                border-width: 10px 0px !important;
                text-align: center !important;
            }}

            .es-adaptive table,
            .es-btn-fw,
            .es-btn-fw-brdr,
            .es-left,
            .es-right {{
                width: 100% !important;
            }}

            .es-content table,
            .es-header table,
            .es-footer table,
            .es-content,
            .es-footer,
            .es-header {{
                width: 100% !important;
                max-width: 600px !important;
            }}

            .es-adapt-td {{
                display: block !important;
                width: 100% !important;
            }}

            .adapt-img {{
                width: 100% !important;
                height: auto !important;
            }}

            .es-m-p0 {{
                padding: 0px !important;
            }}

            .es-m-p0r {{
                padding-right: 0px !important;
            }}

            .es-m-p0l {{
                padding-left: 0px !important;
            }}

            .es-m-p0t {{
                padding-top: 0px !important;
            }}

            .es-m-p0b {{
                padding-bottom: 0 !important;
            }}

            .es-m-p20b {{
                padding-bottom: 20px !important;
            }}

            .es-mobile-hidden,
            .es-hidden {{
                display: none !important;
            }}

            .es-desk-hidden {{
                display: table-row !important;
                width: auto !important;
                overflow: visible !important;
                float: none !important;
                max-height: inherit !important;
                line-height: inherit !important;
            }}

            .es-desk-menu-hidden {{
                display: table-cell !important;
            }}

            table.es-table-not-adapt,
            .esd-block-html table {{
                width: auto !important;
            }}

            table.es-social {{
                display: inline-block !important;
            }}

            table.es-social td {{
                display: inline-block !important;
            }}
        }}

        /* END RESPONSIVE STYLES */
        .es-p-default {{
            padding-top: 20px;
            padding-right: 35px;
            padding-bottom: 0px;
            padding-left: 35px;
        }}

        .es-p-all-default {{
            padding: 0px;
        }}
    </style>
</head>

<body>
    <div class=""es-wrapper-color"">
        <!--[if gte mso 9]>
			<v:background xmlns:v=""urn:schemas-microsoft-com:vml"" fill=""t"">
				<v:fill type=""tile"" color=""#eeeeee""></v:fill>
			</v:background>
		<![endif]-->
        <table class=""es-wrapper"" width=""100%"" cellspacing=""0"" cellpadding=""0"">
            <tbody>
                <tr>
                    <td class=""esd-email-paddings"" valign=""top"">
                        <table class=""es-content esd-header-popover"" cellspacing=""0"" cellpadding=""0"" align=""center"">
                            <tbody>
                                <tr></tr>
                                <tr>
                                    <td class=""esd-stripe"" esd-custom-block-id=""7799"" align=""center"">
                                        <table class=""es-header-body"" style=""background-color: rgb(255, 255, 255);"" width=""600"" cellspacing=""0"" cellpadding=""0"" bgcolor=""#ffffff"" align=""center"">
                                            <tbody>
                                                <tr>
                                                    <td class=""esd-structure es-p20t es-p20b es-p20r es-p20l"" align=""left"" bgcolor=""transparent"" style=""background-color: transparent;"">
                                                        <!--[if mso]><table width=""560"" cellpadding=""0"" cellspacing=""0""><tr><td width=""410"" valign=""top""><![endif]-->
                                                        <table cellspacing=""0"" cellpadding=""0"" align=""left"" class=""es-left"">
                                                            <tbody>
                                                                <tr>
                                                                    <td class=""esd-container-frame es-m-p20b"" width=""410"" valign=""top"" align=""center"">
                                                                        <table width=""100%"" cellspacing=""0"" cellpadding=""0"">
                                                                            <tbody>
                                                                                <tr>
                                                                                    <td class=""esd-block-text es-m-txt-c es-p30t es-p20l"" align=""center"">
                                                                                        <h1 style=""color: #333333; line-height: 100%; text-align: center; font-family: 'open sans', 'helvetica neue', helvetica, arial, sans-serif;"">مصلحة الاحوال المدنية</h1>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td align=""center"" class=""esd-block-text es-p20l"">
                                                                                        <p style=""line-height: 120%; font-size: 20px; color: #333333;""><strong>دولة ليبيا</strong></p>
                                                                                    </td>
                                                                                </tr>
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                        <!--[if mso]></td><td width=""20""></td><td width=""130"" valign=""top""><![endif]-->
                                                        <table cellpadding=""0"" cellspacing=""0"" class=""es-right"" align=""right"">
                                                            <tbody>
                                                                <tr>
                                                                    <td width=""130"" align=""left"" class=""esd-container-frame"">
                                                                        <table cellpadding=""0"" cellspacing=""0"" width=""100%"">
                                                                            <tbody>
                                                                                <tr>
                                                                                    <td align=""center"" class=""esd-block-image""><a target=""_blank""><img src=""https://drive.google.com/uc?export=view&id=1n6aPFQDxPhzKQvcp0p0nfVOrYzH4_x1T"" style=""width: 100px; max-width: 100%; height: 100px; display: block;"" alt width=""100""></a></td>
                                                                                </tr>
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                        <!--[if mso]></td></tr></table><![endif]-->
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <table class=""es-content"" cellspacing=""0"" cellpadding=""0"" align=""center"">
                            <tbody>
                                <tr>
                                    <td class=""esd-stripe"" align=""center"">
                                        <table class=""es-content-body"" width=""600"" cellspacing=""0"" cellpadding=""0"" bgcolor=""#ffffff"" align=""center"">
                                            <tbody>
                                                <tr>
                                                    <td class=""esd-structure es-p20b es-p20r es-p20l"" esd-custom-block-id=""7811"" align=""left"">
                                                        <table width=""100%"" cellspacing=""0"" cellpadding=""0"">
                                                            <tbody>
                                                                <tr>
                                                                    <td class=""esd-container-frame"" width=""560"" valign=""top"" align=""center"">
                                                                        <hr>
                                                                        <table width=""100%"" cellspacing=""0"" cellpadding=""0"">
                                                                            <tbody>
                                                                                <tr>
                                                                                    <td class=""esd-block-text es-p10t es-p5b"" align=""left"">
                                                                                        <h3 style=""color: #333333; text-align: right;"">&nbsp;الي السيد/ة</h3>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td class=""esd-block-text es-p5t es-p5b"" align=""left"">
                                                                                        <h3 style=""color: #333333; text-align: right;"">
                                                                                            {0}
                                                                                            حول 
                                                                                            {1}
                                                                                        </h3>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td class=""esd-block-text es-p5t es-p10b"" align=""right"">
                                                                                        <p style=""font-size: 16px; color: rgb(119, 119, 119); line-height: 150%; text-align: right;""> {2} </p>
                                                                                    </td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <td class=""esd-block-text es-p40t"" align=""right"">
                                                                                        <span style=""color: #333333; text-align: right;font-size=25px"">{3}</span><br/>
                                                                                           <span style=""font-size: 16px; color: #777777;"">{4}</span>
                                                                                    </td>
                                                                                </tr>
                                                                               
                                                                                <tr>
                                                                                    <td class=""esd-block-text"" align=""right"">
                                                                                        <p style=""font-size: 16px; color: #777777;"">{5}</p>
                                                                                    </td>
                                                                                </tr>
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <table class=""es-content esd-footer-popover"" cellspacing=""0"" cellpadding=""0"" align=""center"">
                            <tbody>
                                <tr></tr>
                                <tr>
                                    <td class=""esd-stripe"" align=""center"">
                                        <table class=""es-header-body"" style=""background-color: rgb(236, 235, 235);"" width=""600"" cellspacing=""0"" cellpadding=""0"" bgcolor=""#ecebeb"" align=""center"">
                                            <tbody>
                                                <tr>
                                                    <td class=""esd-structure es-p5t es-p35r es-p35l"" align=""left"">
                                                        <table cellpadding=""0"" cellspacing=""0"" width=""100%"">
                                                            <tbody>
                                                                <tr>
                                                                    <td width=""530"" align=""left"" class=""esd-container-frame"">
                                                                        <table cellpadding=""0"" cellspacing=""0"" width=""100%"">
                                                                            <tbody>
                                                                                <tr>
                                                                                    <td align=""center"" class=""esd-block-text"" esd-links-color=""#8987cb"" esd-links-underline=""underline"">
                                                                                        <p style=""line-height: 120%; font-size: 20px; color: #666666;"">يمكن الوصول الي الموقع <span style=""font-size:16px;""><strong><a href=""www.google.com"" style=""color: #8987cb; text-decoration: underline; font-size: 16px;""> بالضغط هنا </a></strong></span></p>
                                                                                    </td>
                                                                                </tr>
                                                                            </tbody>
                                                                        </table>
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>", AdTypeName, newMessageDTO.Subject, newMessageDTO.Content, userSender.UserName, userSender.BranchName, fillAttach);

                var multipart = new Multipart("mixed");
                multipart.Add(bodyBuilder.ToMessageBody());
                messageEmail.Body = multipart;

                using (var clinet = new SmtpClient())
                {
                    await clinet.ConnectAsync("smtp.gmail.com", 587, false);

                    await clinet.AuthenticateAsync("*****@*****.**", "P@$$w0rd123");

                    await clinet.SendAsync(messageEmail);

                    await clinet.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
            }
        }
Beispiel #9
0
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
            .SendAsync(NotificationHub.NotificationEvent, "Newsletter Started");

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                .SendAsync(NotificationHub.NotificationEvent, "Newsletter Email Settings Not Configured");

                return;
            }

            try
            {
                var plexSettings = await _plexSettings.GetSettingsAsync();

                var embySettings = await _embySettings.GetSettingsAsync();

                var jellyfinSettings = await _jellyfinSettings.GetSettingsAsync();

                var customization = await _customizationSettings.GetSettingsAsync();

                var moviesContents = new List <IMediaServerContent>();
                var seriesContents = new List <IMediaServerEpisode>();
                if (plexSettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_plex, test));
                    seriesContents.AddRange(GetSeriesContent(_plex, test));
                }
                if (embySettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_emby, test));
                    seriesContents.AddRange(GetSeriesContent(_emby, test));
                }
                if (jellyfinSettings.Enable)
                {
                    moviesContents.AddRange(await GetMoviesContent(_jellyfin, test));
                    seriesContents.AddRange(GetSeriesContent(_jellyfin, test));
                }

                var albumsContents = GetMusicContent(_lidarrAlbumRepository, test);

                var body = await BuildHtml(moviesContents, seriesContents, albumsContents, settings);

                if (body.IsNullOrEmpty())
                {
                    return;
                }

                if (!test)
                {
                    var users = new List <OmbiUser>();
                    foreach (var emails in settings.ExternalEmails)
                    {
                        users.Add(new OmbiUser
                        {
                            UserName = emails,
                            Email    = emails
                        });
                    }

                    // Get the users to send it to
                    users.AddRange(await _userManager.GetUsersInRoleAsync(OmbiRoles.ReceivesNewsletter));
                    if (!users.Any())
                    {
                        return;
                    }

                    var messageContent = ParseTemplate(template, customization);
                    var email          = new NewsletterTemplate();

                    foreach (var user in users.DistinctBy(x => x.Email))
                    {                        // Get the users to send it to
                        if (user.Email.IsNullOrEmpty())
                        {
                            continue;
                        }

                        var url  = GenerateUnsubscribeLink(customization.ApplicationUrl, user.Id);
                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo, url);

                        var bodyBuilder = new BodyBuilder
                        {
                            HtmlBody = html,
                        };

                        var message = new MimeMessage
                        {
                            Body    = bodyBuilder.ToMessageBody(),
                            Subject = messageContent.Subject
                        };

                        // Send the message to the user
                        message.To.Add(new MailboxAddress(user.Email.Trim(), user.Email.Trim()));

                        // Send the email
                        await _email.Send(message, emailSettings);
                    }

                    // Now add all of this to the Recently Added log
                    var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                    AddToRecentlyAddedLog(moviesContents, recentlyAddedLog);
                    AddToRecentlyAddedLog(seriesContents, recentlyAddedLog);
                    await _recentlyAddedLog.AddRange(recentlyAddedLog);
                }
                else
                {
                    var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                    foreach (var a in admins)
                    {
                        if (a.Email.IsNullOrEmpty())
                        {
                            continue;
                        }

                        var unsubscribeLink = GenerateUnsubscribeLink(customization.ApplicationUrl, a.Id);

                        var messageContent = ParseTemplate(template, customization);

                        var email = new NewsletterTemplate();

                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo, unsubscribeLink);

                        await _email.Send(
                            new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                            emailSettings);
                    }
                }
            }
            catch (Exception e)
            {
                await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
                .SendAsync(NotificationHub.NotificationEvent, "Newsletter Failed");

                _log.LogError(e, "Error when attempting to create newsletter");
                throw;
            }

            await _notification.Clients.Clients(NotificationHub.AdminConnectionIds)
            .SendAsync(NotificationHub.NotificationEvent, "Newsletter Finished");
        }
        public IActionResult ToOrder(CustomerInfoModel model)
        {
            //Get cart from Session
            var cart = HttpContext.Session.GetString("cart");

            if (cart == null)
            {
                return(View("ErrorOrder"));
            }

            List <CartModel> dataCart = JsonConvert.DeserializeObject <List <CartModel> >(cart);

            if (ModelState.IsValid)
            {
                //Get info of customer
                var customerinfor = _db.CustomerInfos.Where(x => x.UserName == this.User.Identity.Name).FirstOrDefault();
                //CustomerInfoModel contains order infomation
                if (customerinfor != null)
                {
                    customerinfor.FullName    = model.FullName;
                    customerinfor.Address     = model.Address;
                    customerinfor.PhoneNumber = model.PhoneNumber;
                    customerinfor.ProvinceID  = model.ProvinceID;
                    customerinfor.DistrictID  = model.DistrictID;
                    customerinfor.WardID      = model.WardID;
                    customerinfor.Note        = model.Note;
                    //save modified informations to database
                    _db.SaveChanges();
                }

                //Create order
                var OrdersModel = new Order();
                if (model.UserName == null)
                {
                    OrdersModel.UserName = "******";
                }
                else
                {
                    OrdersModel.UserName = model.UserName;
                }
                OrdersModel.FullName    = model.FullName;
                OrdersModel.Address     = model.Address;
                OrdersModel.PhoneNumber = model.PhoneNumber;
                OrdersModel.ProvinceID  = model.ProvinceID;
                OrdersModel.DistrictID  = model.DistrictID;
                OrdersModel.WardID      = model.WardID;
                OrdersModel.OrderDate   = DateTime.Now;
                OrdersModel.Total       = model.Total;
                OrdersModel.ShipFee     = model.ShipFee;

                _db.Orders.Add(OrdersModel);

                _db.SaveChanges();

                for (int i = 0; i < dataCart.Count; i++)
                {
                    var OrdersDetailModel = new OrderDetail();

                    OrdersDetailModel.OrderId     = OrdersModel.OrderId;
                    OrdersDetailModel.ProductId   = dataCart[i].Product.ID;
                    OrdersDetailModel.ProductName = dataCart[i].Product.ProductName;
                    OrdersDetailModel.Quantity    = dataCart[i].Quantity;
                    OrdersDetailModel.UnitPrice   = dataCart[i].DetailProduct.UnitPriceNew;
                    OrdersDetailModel.ColorSize   = dataCart[i].DetailProduct.NameColor;
                    _db.OrderDetails.Add(OrdersDetailModel);
                }

                _db.SaveChanges();

                //Send Email if login

                #region Email

                if (customerinfor != null)
                {
                    if (!string.IsNullOrEmpty(customerinfor.Email))
                    {
                        var    mailRequest   = new MailRequest();
                        string OrderIDFormat = OrdersModel.OrderId.ToString("#00000000");
                        mailRequest.ToEmail = customerinfor.Email; //get user email
                        mailRequest.Subject = $"Order Confirmation #{OrderIDFormat} - Estore247";
                        mailRequest.Body    = "";

                        var orderDetails = _db.OrderDetails.Where(x => x.OrderId == OrdersModel.OrderId).ToList();

                        var bodyorderdetail = CreatOderDetailHTML(orderDetails, OrdersModel.Total.Value, OrdersModel.ShipFee.Value);

                        string ward = _db.CT_Wards.Where(m => m.ID == OrdersModel.WardID)
                                      .Select(m => m.Name)
                                      .FirstOrDefault();
                        string district = _db.CT_Districts.Where(m => m.ID == OrdersModel.DistrictID)
                                          .Select(m => m.Name)
                                          .FirstOrDefault();
                        string province = _db.CT_Provinces.Where(m => m.ID == OrdersModel.ProvinceID)
                                          .Select(m => m.Name)
                                          .FirstOrDefault();

                        string address = OrdersModel.Address + ", " + ward + ", " + district + ", " + province;

                        // Read file template html
                        var webRoot = _env.WebRootPath;

                        string pathToFile = Path.Combine(this._env.WebRootPath, "Template")
                                            + Path.DirectorySeparatorChar.ToString()
                                            + "EmailOrder.html";

                        var builder = new BodyBuilder();
                        using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                        {
                            builder.HtmlBody = SourceReader.ReadToEnd();
                        }
                        //Render order ID: 10 --> #0000010
                        mailRequest.Body = string.Format(builder.HtmlBody,
                                                         OrdersModel.FullName,
                                                         "#" + (OrdersModel.OrderId.ToString("#00000000")),
                                                         string.Format("{0:dd/MM/yyyy hh:mm:ss tt}", OrdersModel.OrderDate),
                                                         address
                                                         , OrdersModel.PhoneNumber
                                                         , bodyorderdetail);

                        mailService.SendEmailAsync(mailRequest);
                    }
                }

                #endregion Email

                //Clear Cart session
                HttpContext.Session.Remove("cart");
                return(RedirectToAction("ToOrder"));
            }
            return(View("ErrorOrder"));
        }
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

                mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                using var client = GetSmtpClient();
                SetProgress(40, "Connect to host");

                client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                               SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                if (SmtpSettings.EnableAuth)
                {
                    SetProgress(60, "Authenticate");

                    client.Authenticate(SmtpSettings.CredentialsUserName,
                                        SmtpSettings.CredentialsUserPassword, cancellationToken);
                }

                SetProgress(80, "Send test message");

                client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
Beispiel #12
0
        static MimeMessage ExtractTnefMessage(TnefReader reader)
        {
            var builder = new BodyBuilder();
            var message = new MimeMessage();

            while (reader.ReadNextAttribute())
            {
                if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
                {
                    break;
                }

                if (reader.AttributeLevel != TnefAttributeLevel.Message)
                {
                    Assert.Fail("Unknown attribute level: {0}", reader.AttributeLevel);
                }

                var prop = reader.TnefPropertyReader;

                switch (reader.AttributeTag)
                {
                case TnefAttributeTag.RecipientTable:
                    ExtractRecipientTable(reader, message);
                    break;

                case TnefAttributeTag.MapiProperties:
                    ExtractMapiProperties(reader, message, builder);
                    break;

                case TnefAttributeTag.DateSent:
                    message.Date = prop.ReadValueAsDateTime();
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, message.Date);
                    break;

                case TnefAttributeTag.Body:
                    builder.TextBody = prop.ReadValueAsString();
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, builder.TextBody);
                    break;

                case TnefAttributeTag.TnefVersion:
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, prop.ReadValueAsInt32());
                    break;

                case TnefAttributeTag.OemCodepage:
                    int codepage = prop.ReadValueAsInt32();
                    try {
                        var encoding = Encoding.GetEncoding(codepage);
                        Console.WriteLine("Message Attribute: OemCodepage = {0}", encoding.HeaderName);
                    }
                    catch {
                        Console.WriteLine("Message Attribute: OemCodepage = {0}", codepage);
                    }
                    break;

                default:
                    Console.WriteLine("Message Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue());
                    break;
                }
            }

            if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
            {
                ExtractAttachments(reader, builder);
            }
            else
            {
                Console.WriteLine("no attachments");
            }

            message.Body = builder.ToMessageBody();

            return(message);
        }
Beispiel #13
0
        static void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var             attachMethod = TnefAttachMethod.ByValue;
            var             filter = new BestEncodingFilter();
            var             prop = reader.TnefPropertyReader;
            MimePart        attachment = null;
            int             outIndex, outLength;
            TnefAttachFlags flags;

            string[] mimeType;
            byte[]   attachData;
            DateTime time;
            string   text;

            Console.WriteLine("Extracting attachments...");

            do
            {
                if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
                {
                    Assert.Fail("Expected attachment attribute level: {0}", reader.AttributeLevel);
                }

                switch (reader.AttributeTag)
                {
                case TnefAttributeTag.AttachRenderData:
                    Console.WriteLine("Attachment Attribute: {0}", reader.AttributeTag);
                    attachMethod = TnefAttachMethod.ByValue;
                    attachment   = new MimePart();
                    break;

                case TnefAttributeTag.Attachment:
                    Console.WriteLine("Attachment Attribute: {0}", reader.AttributeTag);
                    if (attachment == null)
                    {
                        break;
                    }

                    while (prop.ReadNextProperty())
                    {
                        switch (prop.PropertyTag.Id)
                        {
                        case TnefPropertyId.AttachLongFilename:
                            attachment.FileName = prop.ReadValueAsString();

                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            break;

                        case TnefPropertyId.AttachFilename:
                            if (attachment.FileName == null)
                            {
                                attachment.FileName = prop.ReadValueAsString();
                                Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            }
                            else
                            {
                                Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString());
                            }
                            break;

                        case TnefPropertyId.AttachContentLocation:
                            text = prop.ReadValueAsString();
                            if (Uri.IsWellFormedUriString(text, UriKind.Absolute))
                            {
                                attachment.ContentLocation = new Uri(text, UriKind.Absolute);
                            }
                            else if (Uri.IsWellFormedUriString(text, UriKind.Relative))
                            {
                                attachment.ContentLocation = new Uri(text, UriKind.Relative);
                            }
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;

                        case TnefPropertyId.AttachContentBase:
                            text = prop.ReadValueAsString();
                            attachment.ContentBase = new Uri(text, UriKind.Absolute);
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;

                        case TnefPropertyId.AttachContentId:
                            attachment.ContentId = prop.ReadValueAsString();
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentId);
                            break;

                        case TnefPropertyId.AttachDisposition:
                            text = prop.ReadValueAsString();
                            if (attachment.ContentDisposition == null)
                            {
                                attachment.ContentDisposition = new ContentDisposition(text);
                            }
                            else
                            {
                                attachment.ContentDisposition.Disposition = text;
                            }
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;

                        case TnefPropertyId.AttachMethod:
                            attachMethod = (TnefAttachMethod)prop.ReadValueAsInt32();
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachMethod);
                            break;

                        case TnefPropertyId.AttachMimeTag:
                            text     = prop.ReadValueAsString();
                            mimeType = text.Split('/');
                            if (mimeType.Length == 2)
                            {
                                attachment.ContentType.MediaType    = mimeType[0].Trim();
                                attachment.ContentType.MediaSubtype = mimeType[1].Trim();
                            }
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;

                        case TnefPropertyId.AttachFlags:
                            flags = (TnefAttachFlags)prop.ReadValueAsInt32();
                            if ((flags & TnefAttachFlags.RenderedInBody) != 0)
                            {
                                if (attachment.ContentDisposition == null)
                                {
                                    attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Inline);
                                }
                                else
                                {
                                    attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
                                }
                            }
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, flags);
                            break;

                        case TnefPropertyId.AttachData:
                            var stream  = prop.GetRawValueReadStream();
                            var content = new MemoryStream();
                            var guid    = new byte[16];

                            if (attachMethod == TnefAttachMethod.EmbeddedMessage)
                            {
                                var tnef = new TnefPart();

                                foreach (var param in attachment.ContentType.Parameters)
                                {
                                    tnef.ContentType.Parameters[param.Name] = param.Value;
                                }

                                if (attachment.ContentDisposition != null)
                                {
                                    tnef.ContentDisposition = attachment.ContentDisposition;
                                }

                                attachment = tnef;
                            }

                            stream.Read(guid, 0, 16);

                            stream.CopyTo(content, 4096);

                            var buffer = content.GetBuffer();
                            filter.Flush(buffer, 0, (int)content.Length, out outIndex, out outLength);
                            attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                            attachment.ContentObject           = new ContentObject(content);
                            filter.Reset();

                            Console.WriteLine("Attachment Property: {0} has GUID {1}", prop.PropertyTag.Id, new Guid(guid));

                            builder.Attachments.Add(attachment);
                            break;

                        case TnefPropertyId.DisplayName:
                            attachment.ContentType.Name = prop.ReadValueAsString();
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentType.Name);
                            break;

                        case TnefPropertyId.AttachSize:
                            if (attachment.ContentDisposition == null)
                            {
                                attachment.ContentDisposition = new ContentDisposition();
                            }

                            attachment.ContentDisposition.Size = prop.ReadValueAsInt64();
                            Console.WriteLine("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentDisposition.Size.Value);
                            break;

                        default:
                            Console.WriteLine("Attachment Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue());
                            break;
                        }
                    }
                    break;

                case TnefAttributeTag.AttachData:
                    Console.WriteLine("Attachment Attribute: {0}", reader.AttributeTag);
                    if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
                    {
                        break;
                    }

                    attachData = prop.ReadValueAsBytes();
                    filter.Flush(attachData, 0, attachData.Length, out outIndex, out outLength);
                    attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                    attachment.ContentObject           = new ContentObject(new MemoryStream(attachData, false));
                    filter.Reset();

                    builder.Attachments.Add(attachment);
                    break;

                case TnefAttributeTag.AttachCreateDate:
                    time = prop.ReadValueAsDateTime();

                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.CreationDate = time;
                    }

                    Console.WriteLine("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
                    break;

                case TnefAttributeTag.AttachModifyDate:
                    time = prop.ReadValueAsDateTime();

                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.ModificationDate = time;
                    }

                    Console.WriteLine("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
                    break;

                case TnefAttributeTag.AttachTitle:
                    text = prop.ReadValueAsString();

                    if (attachment != null && string.IsNullOrEmpty(attachment.FileName))
                    {
                        attachment.FileName = text;
                    }

                    Console.WriteLine("Attachment Attribute: {0} = {1}", reader.AttributeTag, text);
                    break;

                default:
                    Console.WriteLine("Attachment Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue());
                    break;
                }
            } while (reader.ReadNextAttribute());
        }
Beispiel #14
0
        static void ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
        {
            var prop = reader.TnefPropertyReader;

            while (prop.ReadNextProperty())
            {
                switch (prop.PropertyTag.Id)
                {
                case TnefPropertyId.InternetMessageId:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.MessageId = prop.ReadValueAsString();
                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, message.MessageId);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for Message-Id: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.Subject:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.Subject = prop.ReadValueAsString();
                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, message.Subject);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for Subject: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.RtfCompressed:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var rtf = new TextPart("rtf");
                        rtf.ContentType.Name = "body.rtf";

                        var converter = new RtfCompressedToRtf();
                        var content   = new MemoryStream();

                        using (var filtered = new FilteredStream(content)) {
                            filtered.Add(converter);

                            using (var compressed = prop.GetRawValueReadStream()) {
                                compressed.CopyTo(filtered, 4096);
                                filtered.Flush();
                            }
                        }

                        rtf.ContentObject = new ContentObject(content);
                        content.Position  = 0;

                        builder.Attachments.Add(rtf);

                        Console.WriteLine("Message Property: {0} = <compressed rtf data>", prop.PropertyTag.Id);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.BodyHtml:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var html = new TextPart("html");
                        html.ContentType.Name = "body.html";
                        html.Text             = prop.ReadValueAsString();

                        builder.Attachments.Add(html);

                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, html.Text);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.Body:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var plain = new TextPart("plain");
                        plain.ContentType.Name = "body.txt";
                        plain.Text             = prop.ReadValueAsString();

                        builder.Attachments.Add(plain);

                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, plain.Text);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                default:
                    object value;

                    try {
                        value = prop.ReadValue();
                    } catch {
                        value = null;
                    }

                    Console.WriteLine("Message Property (unhandled): {0} = {1}", prop.PropertyTag.Id, value);
                    break;
                }
            }
        }
Beispiel #15
0
		static void ExtractAttachments (TnefReader reader, BodyBuilder builder)
		{
			var filter = new BestEncodingFilter ();
			var prop = reader.TnefPropertyReader;
			MimePart attachment = null;
			int outIndex, outLength;
			byte[] attachData;
			string text;

			do {
				if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
					break;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.AttachRenderData:
					attachment = new MimePart ();
					builder.Attachments.Add (attachment);
					break;
				case TnefAttributeTag.Attachment:
					if (attachment == null)
						break;

					while (prop.ReadNextProperty ()) {
						switch (prop.PropertyTag.Id) {
						case TnefPropertyId.AttachLongFilename:
							attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachFilename:
							if (attachment.FileName == null)
								attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachContentLocation:
							text = prop.ReadValueAsString ();
							if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
								attachment.ContentLocation = new Uri (text, UriKind.Absolute);
							else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
								attachment.ContentLocation = new Uri (text, UriKind.Relative);
							break;
						case TnefPropertyId.AttachContentBase:
							text = prop.ReadValueAsString ();
							attachment.ContentBase = new Uri (text, UriKind.Absolute);
							break;
						case TnefPropertyId.AttachContentId:
							attachment.ContentId = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachDisposition:
							text = prop.ReadValueAsString ();
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition (text);
							else
								attachment.ContentDisposition.Disposition = text;
							break;
						case TnefPropertyId.AttachData:
							// TODO: implement this...
							break;
						}
					}
					break;
				case TnefAttributeTag.AttachData:
					if (attachment == null)
						break;

					attachData = prop.ReadValueAsBytes ();
					filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
					attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.EightBit);
					attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
					filter.Reset ();
					break;
				}
			} while (reader.ReadNextAttribute ());
		}
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName     = Input.Email,
                    Email        = Input.Email,
                    ClientId     = Input.ClientId,
                    PhoneNumber  = Input.PhoneNumber,
                    PozitieFirma = Input.PozitieFirma,
                    Nume         = Input.Nume,
                    Rol          = Input.Rol
                };
                // creare user
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("Utilizatorul si-a creat un cont nou cu parola.");

                    // Check if the role exists
                    if (!await _roleManager.RoleExistsAsync(ConstantVar.Rol_Admin))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(ConstantVar.Rol_Admin));
                    }
                    if (!await _roleManager.RoleExistsAsync(ConstantVar.Rol_Admin_Firma))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(ConstantVar.Rol_Admin_Firma));
                    }
                    if (!await _roleManager.RoleExistsAsync(ConstantVar.Rol_User_Individual))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(ConstantVar.Rol_User_Individual));
                    }
                    if (!await _roleManager.RoleExistsAsync(ConstantVar.Rol_Angajat))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(ConstantVar.Rol_Angajat));
                    }

                    IEnumerable <EmailAddress> emailAddresses = new List <EmailAddress>()
                    {
                        new EmailAddress()
                        {
                            Address = user.Email
                        }
                    };

                    var pathToFile = _env.WebRootPath
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "templates"
                                     + Path.DirectorySeparatorChar.ToString()
                                     + "EmailTemplates"
                                     + Path.DirectorySeparatorChar.ToString();

                    var builder = new BodyBuilder();

                    if (user.Rol == null)
                    {
                        await _userManager.AddToRoleAsync(user, ConstantVar.Rol_User_Individual);
                    }
                    else
                    {
                        // trimitere mail cu credentialele utilizatorului, deoarece contul este creat de administrator
                        using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile + "RegisterCredentials.html"))
                        {
                            builder.HtmlBody = SourceReader.ReadToEnd();
                        }

                        string messageBodyCredentials = string.Format(builder.HtmlBody,
                                                                      user.Nume,
                                                                      _context.Client.FirstOrDefault(x => x.ClientId == user.ClientId).Denumire,
                                                                      user.Email,
                                                                      Input.Password
                                                                      );

                        var messageCredentials = new Message(emailAddresses, "Credentiale cont platforma Contsal", messageBodyCredentials);
                        _emailSender.SendEmail(messageCredentials);

                        await _userManager.AddToRoleAsync(user, user.Rol);
                    }

                    // Confirmation Mail
                    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, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    builder = new BodyBuilder();
                    using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile + "EmailConfirmation.html"))
                    {
                        builder.HtmlBody = SourceReader.ReadToEnd();
                    }

                    string messageBody = string.Format(builder.HtmlBody,
                                                       user.Nume,
                                                       HtmlEncoder.Default.Encode(callbackUrl)
                                                       );

                    var message = new Message(emailAddresses, "Confirmare cont mail ", messageBody);
                    _emailSender.SendEmail(message);

                    // sign in user after registration
                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        if (user.Rol == null)
                        {
                            await _signInManager.SignInAsync(user, isPersistent : false);

                            return(LocalRedirect(returnUrl));
                        }
                        else
                        {
                            // admin-ul adauga noi Useri si il redirectionam spre lista cu toti Userii
                            return(RedirectToAction("Index", "ApplicationUsers", new { Area = "Admin" }));
                        }
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(Page());
        }
Beispiel #17
0
        static internal bool Send(EmailConfig config, InternetAddressList recipientsTo, InternetAddressList recipientsCc, InternetAddressList recipientsBcc, string subject, bool isHtml, string body, MimeKit.AttachmentCollection attachments)
        {
            if ((recipientsTo == null || recipientsTo.Count == 0) && (recipientsCc == null || recipientsCc.Count == 0) && (recipientsBcc == null || recipientsBcc.Count == 0))
            {
                return(false);
            }

            MimeMessage message     = new MimeMessage();
            BodyBuilder bodyBuilder = new BodyBuilder();

            MailKit.Net.Smtp.SmtpClient smtp = new MailKit.Net.Smtp.SmtpClient();

            // Set the recipients
            message.From.Add(new MailboxAddress(config.DisplayName, config.Address));
            message.To.AddRange(recipientsTo ?? new InternetAddressList());
            message.Cc.AddRange(recipientsCc ?? new InternetAddressList());
            message.Bcc.AddRange(recipientsBcc ?? new InternetAddressList());

            // Set the properties and establish the Smtp server connection
            smtp.Timeout = config.SmtpTimeout;
            try
            {
                smtp.Connect(config.SmtpServer, config.SmtpPort, GetSslOptionsEnumValue(config.SmtpSslOptions));
            }
            catch (Exception ex)
            {
                Error.ProcessError(ex, "Error al conectar al servidor SMTP.");
                return(false);
            }
            string decryptedPassword = string.Empty;

            if (!Encrypt.StringCipher.Decrypt(config.SmtpPassword, Constants.PublicEncryptionPassword, ref decryptedPassword))
            {
                MessageBox.Show("La contraseña de e-mail (SMTP) especificada es incorrecta.", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }
            try
            {
                smtp.Authenticate(new System.Net.NetworkCredential(config.SmtpUserName, decryptedPassword));
            }
            catch (Exception)
            {
                MessageBox.Show("Error al iniciar sesión en el servidor SMTP.", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            // Set the content
            message.Subject = subject ?? string.Empty;
            if (isHtml)
            {
                bodyBuilder.HtmlBody = body;
            }
            else
            {
                bodyBuilder.TextBody = body;
            }

            // Set the attachments
            if (attachments != null)
            {
                foreach (MimeEntity attachment in attachments)
                {
                    bodyBuilder.Attachments.Add(attachment);
                }
            }

            // Set the body
            message.Body = bodyBuilder.ToMessageBody();

            // Send the message
            try
            {
                smtp.Send(message);
            }
            catch (Exception)
            {
                MessageBox.Show("Error al enviar el e-mail.", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            // Closes the Smtp server connection
            try
            {
                smtp.Disconnect(true);
            }
            catch (Exception)
            {
                MessageBox.Show("Error al desconectar al servidor SMTP.", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            return(true);
        }
        public async Task SendEmailAsync(Models.Mail.MailMessage message)
        {
            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_globalSettings.SiteName, _replyEmail));
            mimeMessage.Subject = message.Subject;
            if (!string.IsNullOrWhiteSpace(_replyDomain))
            {
                mimeMessage.MessageId = $"<{Guid.NewGuid()}@{_replyDomain}>";
            }

            foreach (var address in message.ToEmails)
            {
                var punyencoded = CoreHelpers.PunyEncode(address);
                mimeMessage.To.Add(MailboxAddress.Parse(punyencoded));
            }

            if (message.BccEmails != null)
            {
                foreach (var address in message.BccEmails)
                {
                    var punyencoded = CoreHelpers.PunyEncode(address);
                    mimeMessage.Bcc.Add(MailboxAddress.Parse(punyencoded));
                }
            }

            var builder = new BodyBuilder();

            if (!string.IsNullOrWhiteSpace(message.TextContent))
            {
                builder.TextBody = message.TextContent;
            }
            builder.HtmlBody = message.HtmlContent;
            mimeMessage.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                if (_globalSettings.Mail.Smtp.TrustServer)
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                }

                if (!_globalSettings.Mail.Smtp.StartTls && !_globalSettings.Mail.Smtp.Ssl &&
                    _globalSettings.Mail.Smtp.Port == 25)
                {
                    await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port,
                                              MailKit.Security.SecureSocketOptions.None);
                }
                else
                {
                    var useSsl = _globalSettings.Mail.Smtp.Port == 587 && !_globalSettings.Mail.Smtp.SslOverride ?
                                 false : _globalSettings.Mail.Smtp.Ssl;
                    await client.ConnectAsync(_globalSettings.Mail.Smtp.Host, _globalSettings.Mail.Smtp.Port, useSsl);
                }

                if (CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Username) &&
                    CoreHelpers.SettingHasValue(_globalSettings.Mail.Smtp.Password))
                {
                    await client.AuthenticateAsync(_globalSettings.Mail.Smtp.Username,
                                                   _globalSettings.Mail.Smtp.Password);
                }

                await client.SendAsync(mimeMessage);

                await client.DisconnectAsync(true);
            }
        }
Beispiel #19
0
        private MimeMessage FromMailMessage(MailMessage message)
        {
            var submitterAddress = String.IsNullOrWhiteSpace(message.Sender)
                ? _options.DefaultSender
                : message.Sender;

            var mimeMessage = new MimeMessage();

            if (!String.IsNullOrEmpty(submitterAddress))
            {
                mimeMessage.Sender = MailboxAddress.Parse(submitterAddress);
            }

            if (!string.IsNullOrWhiteSpace(message.From))
            {
                foreach (var address in message.From.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.From.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.To))
            {
                foreach (var address in message.To.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.To.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Cc))
            {
                foreach (var address in message.Cc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.Cc.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Bcc))
            {
                foreach (var address in message.Bcc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.Bcc.Add(MailboxAddress.Parse(address));
                }
            }

            if (string.IsNullOrWhiteSpace(message.ReplyTo))
            {
                foreach (var address in mimeMessage.From)
                {
                    mimeMessage.ReplyTo.Add(address);
                }
            }
            else
            {
                foreach (var address in message.ReplyTo.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.ReplyTo.Add(MailboxAddress.Parse(address));
                }
            }

            mimeMessage.Subject = message.Subject;

            var body = new BodyBuilder();

            if (message.IsBodyHtml)
            {
                body.HtmlBody = message.Body;
            }

            if (message.IsBodyText)
            {
                body.TextBody = message.BodyText;
            }

            foreach (var attachment in message.Attachments)
            {
                // Stream must not be null, otherwise it would try to get the filesystem path
                if (attachment.Stream != null)
                {
                    body.Attachments.Add(attachment.Filename, attachment.Stream);
                }
            }

            mimeMessage.Body = body.ToMessageBody();

            return(mimeMessage);
        }
        public async Task <IActionResult> OnPost()
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser
                {
                    UserName  = RegisterViewModel.Email,
                    Email     = RegisterViewModel.Email,
                    Firstname = RegisterViewModel.Firstname,
                    Lastname  = RegisterViewModel.Lastname,
                    CreatedAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CurrentCulture)
                };

                IdentityResult createUser = await _userManager.CreateAsync(user, RegisterViewModel.Password);

                if (createUser.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    // Get TemplateFile located at wwwroot/Template/EmailTemplates/RegisterConfirmation.html.
                    string pathToFile = _env.WebRootPath
                                        + Path.DirectorySeparatorChar.ToString()
                                        + "Template"
                                        + Path.DirectorySeparatorChar.ToString()
                                        + "EmailTemplates"
                                        + Path.DirectorySeparatorChar.ToString()
                                        + "RegisterConfirmation.html";

                    BodyBuilder builder = new BodyBuilder();
                    using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                    {
                        builder.HtmlBody = SourceReader.ReadToEnd();
                    }

                    string subject = "Rejestracja użytkownika";
                    string date    = string.Format("{0:dddd, d MMMM yyyy}", DateTime.Now);
                    string info    = "Aby zmienić hasło kliknij na poniższy przycisk";
                    var    code    = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    string callbackUrl = Url.Page(
                        "/TimeManagement/EmailConfirmation",
                        pageHandler: null,
                        values: new { userId = user.Id, code },
                        protocol: Request.Scheme);
                    string messageBody = string.Format(builder.HtmlBody,
                                                       subject,
                                                       date,
                                                       RegisterViewModel.Email,
                                                       RegisterViewModel.Email,
                                                       RegisterViewModel.Password,
                                                       info,
                                                       callbackUrl
                                                       );
                    Message message = new Message(new string[] { RegisterViewModel.Email }, "Confirm yours account", messageBody, null);
                    await _emailSender.SendEmailAsync(RegisterViewModel.Email, message);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    SuccessRegistrationMessage = "Konto zostało pomyślnie utworzone!";
                    return(RedirectToPage("./Logowanie"));
                }

                ModelState.AddModelError(string.Empty, "Podany Email jest już w użyciu");
            }

            return(Page());
        }
Beispiel #21
0
        public void sendEmailRunner(string email, string subject, string body)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(_config["Smtp:Name"], _config["Smtp:Username"]));
            message.To.Add(new MailboxAddress(email, email));
            message.Subject = subject;

            var bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = body;

            message.Body = bodyBuilder.ToMessageBody();
            using (var client = new SmtpClient())
            {
                try
                {
                    client.Connect(_config["Smtp:Host"], Convert.ToInt32(_config["Smtp:Port"]), SecureSocketOptions.Auto);
                }
                catch (SmtpCommandException ex)
                {
                    _logger.LogDebug("Error trying to connect: {0}", ex.Message);
                    _logger.LogDebug("\tStatusCode: {0}", ex.StatusCode);
                    return;
                }
                catch (SmtpProtocolException ex)
                {
                    _logger.LogDebug("Protocol error while trying to connect: {0}", ex.Message);
                    return;
                }

                // Note: Not all SMTP servers support authentication, but GMail does.
                if (client.Capabilities.HasFlag(SmtpCapabilities.Authentication))
                {
                    try
                    {
                        client.Authenticate(_config["Smtp:Username"], _config["Smtp:Password"]);
                    }
                    catch (AuthenticationException ex)
                    {
                        _logger.LogDebug("Invalid user name or password.");
                        return;
                    }
                    catch (SmtpCommandException ex)
                    {
                        _logger.LogDebug("Error trying to authenticate: {0}", ex.Message);
                        _logger.LogDebug("\tStatusCode: {0}", ex.StatusCode);
                        return;
                    }
                    catch (SmtpProtocolException ex)
                    {
                        _logger.LogDebug("Protocol error while trying to authenticate: {0}", ex.Message);
                        return;
                    }
                }

                try
                {
                    client.Send(message);
                }
                catch (SmtpCommandException ex)
                {
                    _logger.LogDebug("Error sending message: {0}", ex.Message);
                    _logger.LogDebug("\tStatusCode: {0}", ex.StatusCode);

                    switch (ex.ErrorCode)
                    {
                    case SmtpErrorCode.RecipientNotAccepted:
                        _logger.LogDebug("\tRecipient not accepted: {0}", ex.Mailbox);
                        break;

                    case SmtpErrorCode.SenderNotAccepted:
                        _logger.LogDebug("\tSender not accepted: {0}", ex.Mailbox);
                        break;

                    case SmtpErrorCode.MessageNotAccepted:
                        _logger.LogDebug("\tMessage not accepted.");
                        break;
                    }
                }
                catch (SmtpProtocolException ex)
                {
                    _logger.LogDebug("Protocol error while sending message: {0}", ex.Message);
                }

                client.Disconnect(true);
            }
        }
Beispiel #22
0
        static void ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
        {
            var            prop              = reader.TnefPropertyReader;
            var            recipient         = new EmailAddress();
            var            sender            = new EmailAddress();
            string         normalizedSubject = null;
            string         subjectPrefix     = null;
            MailboxAddress mailbox;
            var            msgid = false;

            while (prop.ReadNextProperty())
            {
                switch (prop.PropertyTag.Id)
                {
                case TnefPropertyId.InternetMessageId:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.MessageId = prop.ReadValueAsString();
                        msgid             = true;
                    }
                    break;

                case TnefPropertyId.TnefCorrelationKey:
                    // According to MSDN, PidTagTnefCorrelationKey is a unique key that is
                    // meant to be used to tie the TNEF attachment to the encapsulating
                    // message. It can be a string or a binary blob. It seems that most
                    // implementations use the Message-Id string, so if this property
                    // value looks like a Message-Id, then us it as one (unless we get a
                    // InternetMessageId property, in which case we use that instead.
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        if (!msgid)
                        {
                            var value = prop.ReadValueAsString();

                            if (value.Length > 5 && value[0] == '<' && value[value.Length - 1] == '>' && value.IndexOf('@') != -1)
                            {
                                message.MessageId = value;
                            }
                        }
                    }
                    break;

                case TnefPropertyId.Subject:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.Subject = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.SubjectPrefix:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        subjectPrefix = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.NormalizedSubject:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        normalizedSubject = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.SenderName:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        sender.Name = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.SenderEmailAddress:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        sender.Addr = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.SenderSearchKey:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        sender.SearchKey = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.SenderAddrtype:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        sender.AddrType = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.ReceivedByName:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        recipient.Name = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.ReceivedByEmailAddress:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        recipient.Addr = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.ReceivedBySearchKey:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        recipient.SearchKey = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.ReceivedByAddrtype:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        recipient.AddrType = prop.ReadValueAsString();
                    }
                    break;

                case TnefPropertyId.RtfCompressed:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var rtf = new TextPart("rtf");

                        var converter = new RtfCompressedToRtf();
                        var content   = new MemoryBlockStream();

                        using (var filtered = new FilteredStream(content)) {
                            filtered.Add(converter);

                            using (var compressed = prop.GetRawValueReadStream()) {
                                compressed.CopyTo(filtered, 4096);
                                filtered.Flush();
                            }
                        }

                        rtf.Content      = new MimeContent(content);
                        content.Position = 0;

                        builder.Attachments.Add(rtf);
                    }
                    break;

                case TnefPropertyId.BodyHtml:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var      html = new TextPart("html");
                        Encoding encoding;
                        string   text;

                        if (prop.PropertyTag.ValueTnefType != TnefPropertyType.Unicode)
                        {
                            text = GetHtmlBody(prop, reader.MessageCodepage, out encoding);
                        }
                        else
                        {
                            text     = prop.ReadValueAsString();
                            encoding = CharsetUtils.UTF8;
                        }

                        html.SetText(encoding, text);

                        builder.Attachments.Add(html);
                    }
                    break;

                case TnefPropertyId.Body:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var      plain = new TextPart("plain");
                        Encoding encoding;

                        if (prop.PropertyTag.ValueTnefType != TnefPropertyType.Unicode)
                        {
                            encoding = Encoding.GetEncoding(reader.MessageCodepage);
                        }
                        else
                        {
                            encoding = CharsetUtils.UTF8;
                        }

                        plain.SetText(encoding, prop.ReadValueAsString());

                        builder.Attachments.Add(plain);
                    }
                    break;

                case TnefPropertyId.Importance:
                    // https://msdn.microsoft.com/en-us/library/ee237166(v=exchg.80).aspx
                    switch (prop.ReadValueAsInt32())
                    {
                    case 2: message.Importance = MessageImportance.High; break;

                    case 1: message.Importance = MessageImportance.Normal; break;

                    case 0: message.Importance = MessageImportance.Low; break;
                    }
                    break;

                case TnefPropertyId.Priority:
                    // https://msdn.microsoft.com/en-us/library/ee159473(v=exchg.80).aspx
                    switch (prop.ReadValueAsInt32())
                    {
                    case  1: message.Priority = MessagePriority.Urgent; break;

                    case  0: message.Priority = MessagePriority.Normal; break;

                    case -1: message.Priority = MessagePriority.NonUrgent; break;
                    }
                    break;

                case TnefPropertyId.Sensitivity:
                    // https://msdn.microsoft.com/en-us/library/ee217353(v=exchg.80).aspx
                    // https://tools.ietf.org/html/rfc2156#section-5.3.4
                    switch (prop.ReadValueAsInt32())
                    {
                    case 1: message.Headers[HeaderId.Sensitivity] = "Personal"; break;

                    case 2: message.Headers[HeaderId.Sensitivity] = "Private"; break;

                    case 3: message.Headers[HeaderId.Sensitivity] = "Company-Confidential"; break;

                    case 0: message.Headers.Remove(HeaderId.Sensitivity); break;
                    }
                    break;
                }
            }

            if (string.IsNullOrEmpty(message.Subject) && !string.IsNullOrEmpty(normalizedSubject))
            {
                if (!string.IsNullOrEmpty(subjectPrefix))
                {
                    message.Subject = subjectPrefix + normalizedSubject;
                }
                else
                {
                    message.Subject = normalizedSubject;
                }
            }

            if (sender.TryGetMailboxAddress(out mailbox))
            {
                message.From.Add(mailbox);
            }

            if (recipient.TryGetMailboxAddress(out mailbox))
            {
                message.To.Add(mailbox);
            }
        }
Beispiel #23
0
        public Task Send(EmailTemplateData templateData, List <string> recipients, EmailTemplate template = EmailTemplate.Generic)
        {
            var email = new MimeMessage();

            email.Sender      = MailboxAddress.Parse(Options.EmailUser);
            email.Sender.Name = "Crowd Order Team";
            foreach (var recipient in recipients)
            {
                email.To.Add(MailboxAddress.Parse(recipient));
            }
            if (_configuration["Environment"].ToLower() != "dev")
            {
                email.Bcc.Add(MailboxAddress.Parse(Options.EmailUser));
            }


            email.Subject = templateData.Subject;
            var    builder = new BodyBuilder();
            string tPath   = Directory.GetCurrentDirectory();
            var    hPath   = Directory.GetCurrentDirectory();

            switch (template)
            {
            case EmailTemplate.Generic:
                hPath += _configuration["EmailPaths:Generic.html"].ToLower();
                tPath += _configuration["EmailPaths:Generic.txt"].ToLower();
                break;

            case EmailTemplate.Welcome:
                hPath += _configuration["EmailPaths:Welcome.html"].ToLower();
                tPath += _configuration["EmailPaths:Welcome.txt"].ToLower();
                break;

            case EmailTemplate.PartnerPlain:
                hPath += _configuration["EmailPaths:Plain.html"].ToLower();
                tPath += _configuration["EmailPaths:Plain.txt"].ToLower();
                break;

            case EmailTemplate.ConnectionEmail:
                hPath += _configuration["EmailPaths:PlainConnect.html"].ToLower();
                tPath += _configuration["EmailPaths:PlainConnect.txt"].ToLower();
                break;

            default:
                hPath += @"\wwwroot\emails\generic.html";
                tPath += @"\wwwroot\emails\Generic.txt";
                break;
            }
            //HTML
            StreamReader str      = new StreamReader(hPath);
            string       mailText = str.ReadToEnd();

            str.Close();
            mailText = mailText
                       .Replace("{{h1}}", templateData.H1)
                       .Replace("{{maintext}}", templateData.MainText)
                       .Replace("{{buttontext}}", templateData.ButtonText)
                       .Replace("{{buttonurl}}", templateData.ButtonUrl)
                       .Replace("{{body}}", templateData.Body)
                       .Replace("{{body2}}", templateData.Body2)
                       .Replace("{{greeting}}", templateData.Greeting)
                       .Replace("{{greeting2}}", templateData.Greeting2);


            builder.HtmlBody = mailText;

            //text
            StreamReader str2      = new StreamReader(tPath);
            string       mailText2 = str2.ReadToEnd();

            str2.Close();
            mailText2 = mailText2
                        .Replace("{{h1}}", templateData.H1)
                        .Replace("{{maintext}}", templateData.MainText)
                        .Replace("{{buttontext}}", templateData.ButtonText)
                        .Replace("{{buttonurl}}", templateData.ButtonUrl)
                        .Replace("{{body}}", templateData.Body)
                        .Replace("{{body2}}", templateData.Body2)
                        .Replace("{{greeting}}", templateData.Greeting)
                        .Replace("{{greeting2}}", templateData.Greeting2);



            builder.TextBody = mailText2;

            email.Body = builder.ToMessageBody();
            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
                smtp.Authenticate(Options.EmailUser, Options.EmailUserPassword);
                smtp.Send(email);
                smtp.Disconnect(true);
            }

            return(Task.FromResult(true));
        }
Beispiel #24
0
        static void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var             attachMethod = TnefAttachMethod.ByValue;
            var             filter = new BestEncodingFilter();
            var             prop = reader.TnefPropertyReader;
            MimePart        attachment = null;
            int             outIndex, outLength;
            TnefAttachFlags flags;

            string[] mimeType;
            byte[]   attachData;
            string   text;

            do
            {
                if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
                {
                    break;
                }

                switch (reader.AttributeTag)
                {
                case TnefAttributeTag.AttachRenderData:
                    attachMethod = TnefAttachMethod.ByValue;
                    attachment   = new MimePart();
                    break;

                case TnefAttributeTag.Attachment:
                    if (attachment == null)
                    {
                        break;
                    }

                    attachData = null;

                    while (prop.ReadNextProperty())
                    {
                        switch (prop.PropertyTag.Id)
                        {
                        case TnefPropertyId.AttachLongFilename:
                            attachment.FileName = prop.ReadValueAsString();
                            break;

                        case TnefPropertyId.AttachFilename:
                            if (attachment.FileName == null)
                            {
                                attachment.FileName = prop.ReadValueAsString();
                            }
                            break;

                        case TnefPropertyId.AttachContentLocation:
                            attachment.ContentLocation = prop.ReadValueAsUri();
                            break;

                        case TnefPropertyId.AttachContentBase:
                            attachment.ContentBase = prop.ReadValueAsUri();
                            break;

                        case TnefPropertyId.AttachContentId:
                            text = prop.ReadValueAsString();

                            var buffer = CharsetUtils.UTF8.GetBytes(text);
                            int index  = 0;

                            if (ParseUtils.TryParseMsgId(buffer, ref index, buffer.Length, false, false, out string msgid))
                            {
                                attachment.ContentId = msgid;
                            }
                            break;

                        case TnefPropertyId.AttachDisposition:
                            text = prop.ReadValueAsString();
                            if (ContentDisposition.TryParse(text, out ContentDisposition disposition))
                            {
                                attachment.ContentDisposition = disposition;
                            }
                            break;

                        case TnefPropertyId.AttachData:
                            attachData = prop.ReadValueAsBytes();
                            break;

                        case TnefPropertyId.AttachMethod:
                            attachMethod = (TnefAttachMethod)prop.ReadValueAsInt32();
                            break;

                        case TnefPropertyId.AttachMimeTag:
                            mimeType = prop.ReadValueAsString().Split('/');
                            if (mimeType.Length == 2)
                            {
                                attachment.ContentType.MediaType    = mimeType[0].Trim();
                                attachment.ContentType.MediaSubtype = mimeType[1].Trim();
                            }
                            break;

                        case TnefPropertyId.AttachFlags:
                            flags = (TnefAttachFlags)prop.ReadValueAsInt32();
                            if ((flags & TnefAttachFlags.RenderedInBody) != 0)
                            {
                                if (attachment.ContentDisposition == null)
                                {
                                    attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Inline);
                                }
                                else
                                {
                                    attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
                                }
                            }
                            break;

                        case TnefPropertyId.AttachSize:
                            if (attachment.ContentDisposition == null)
                            {
                                attachment.ContentDisposition = new ContentDisposition();
                            }

                            attachment.ContentDisposition.Size = prop.ReadValueAsInt64();
                            break;

                        case TnefPropertyId.DisplayName:
                            attachment.ContentType.Name = prop.ReadValueAsString();
                            break;
                        }
                    }

                    if (attachData != null)
                    {
                        int count = attachData.Length;
                        int index = 0;

                        if (attachMethod == TnefAttachMethod.EmbeddedMessage)
                        {
                            attachment.ContentTransferEncoding = ContentEncoding.Base64;
                            attachment = PromoteToTnefPart(attachment);
                            count     -= 16;
                            index      = 16;
                        }
                        else if (attachment.ContentType.IsMimeType("text", "*"))
                        {
                            filter.Flush(attachData, index, count, out outIndex, out outLength);
                            attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                            filter.Reset();
                        }
                        else
                        {
                            attachment.ContentTransferEncoding = ContentEncoding.Base64;
                        }

                        attachment.Content = new MimeContent(new MemoryStream(attachData, index, count, false));
                        builder.Attachments.Add(attachment);
                    }
                    break;

                case TnefAttributeTag.AttachCreateDate:
                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.CreationDate = prop.ReadValueAsDateTime();
                    }
                    break;

                case TnefAttributeTag.AttachModifyDate:
                    if (attachment != null)
                    {
                        if (attachment.ContentDisposition == null)
                        {
                            attachment.ContentDisposition = new ContentDisposition();
                        }

                        attachment.ContentDisposition.ModificationDate = prop.ReadValueAsDateTime();
                    }
                    break;

                case TnefAttributeTag.AttachTitle:
                    if (attachment != null && string.IsNullOrEmpty(attachment.FileName))
                    {
                        attachment.FileName = prop.ReadValueAsString();
                    }
                    break;

                case TnefAttributeTag.AttachMetaFile:
                    if (attachment == null)
                    {
                        break;
                    }

                    // TODO: what to do with the meta data?
                    break;

                case TnefAttributeTag.AttachData:
                    if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
                    {
                        break;
                    }

                    attachData = prop.ReadValueAsBytes();

                    if (attachment.ContentType.IsMimeType("text", "*"))
                    {
                        filter.Flush(attachData, 0, attachData.Length, out outIndex, out outLength);
                        attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
                        filter.Reset();
                    }
                    else
                    {
                        attachment.ContentTransferEncoding = ContentEncoding.Base64;
                    }

                    attachment.Content = new MimeContent(new MemoryStream(attachData, false));
                    builder.Attachments.Add(attachment);
                    break;
                }
            } while (reader.ReadNextAttribute());
        }
Beispiel #25
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme);

                string Message = "Please reset your password";

                var subject = "Reset Password Link";

                //get webroot path
                var webRoot = _env.WebRootPath;

                //Get TemplateFile located at wwwroot/templates/ConfirmAccount.html
                var pathToFile = _env.WebRootPath
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "templates"
                                 + Path.DirectorySeparatorChar.ToString()
                                 + "ForgotPassword.html";

                var builder = new BodyBuilder();
                using (StreamReader SourceReader = System.IO.File.OpenText(pathToFile))
                {
                    builder.HtmlBody = SourceReader.ReadToEnd();
                }
                //{0} : Subject
                //{1}:  DateTime
                //{2}: Name
                //{3}:  Message
                //{4}:  callbackUrl

                string messageBody = string.Format(builder.HtmlBody,
                                                   subject,
                                                   String.Format("{0:dddd, d MMMM yyyy}", DateTime.Now),
                                                   user.Name,
                                                   Message,
                                                   callbackUrl
                                                   );


                await _emailSender.SendEmailAsync(Input.Email, subject, messageBody);

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Beispiel #26
0
        public async Task <MimeMessage> GetMessageAsync <T>(string viewName, T model)
        {
            var message = new MimeMessage
            {
                Subject = Subject,
                //SubjectEncoding = Encoding,
                //BodyEncoding = Encoding,
                Priority   = Priority,
                Importance = Importance
            };

            if (Attachments.Count > 0)
            {
                var builder = new BodyBuilder();
                if (!string.IsNullOrWhiteSpace(viewName))
                {
                    if (IsBodyHtml)
                    {
                        builder.HtmlBody = await _viewRenderService.RenderAsString(viewName, model);
                    }
                    else
                    {
                        builder.TextBody = await _viewRenderService.RenderAsString(viewName, model);
                    }
                }

                foreach (var item in Attachments)
                {
                    builder.Attachments.Add(item);
                }

                message.Body = builder.ToMessageBody();
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(viewName))
                {
                    var html = await _viewRenderService.RenderAsString(viewName, model);

                    if (IsBodyHtml)
                    {
                        message.Body = new TextPart(TextFormat.Html)
                        {
                            Text = html
                        };
                    }
                    else
                    {
                        message.Body = new TextPart(TextFormat.Text)
                        {
                            Text = html
                        };
                    }
                }
            }
            if (_Froms != null && _Froms.Count > 0)
            {
                message.From.AddRange(Froms);

                if (message.From.Count > 1)
                {
                    message.Sender = Froms[0];
                }
            }
            else if (From != null)
            {
                message.From.Add(From);
            }

            if (message.From.Count == 0 && !string.IsNullOrWhiteSpace(_settings.FromAddress))
            {
                message.From.Add(new MailboxAddress(_settings.FromDisplayName ?? _settings.FromAddress, _settings.FromAddress));
            }

            if (_To != null && _To.Count > 0)
            {
                message.To.AddRange(To);
            }
            if (_CC != null && _CC.Count > 0)
            {
                message.Cc.AddRange(CC);
            }
            if (_Bcc != null && _Bcc.Count > 0)
            {
                message.Bcc.AddRange(Bcc);
            }

            return(message);
        }
Beispiel #27
0
        //http://www.mimekit.net/docs/html/T_MimeKit_AttachmentCollection.htm
        //https://www.youtube.com/watch?v=Y2X5wtuzuX4
        //https://www.taithienbo.com/send-email-with-attachments-using-mailkit-for-net-core/
        //https://dotnetcoretutorials.com/2017/11/02/using-mailkit-send-receive-email-asp-net-core/
        public async Task SSendEmailAsync(string fromDisplayName,
                                          string fromEmailAddress,
                                          string toName,
                                          string toEmailAddress,
                                          string subject,
                                          string menssage)
        {
            var email = new MimeMessage();

            email.From.Add(new MailboxAddress(fromDisplayName, fromEmailAddress));
            email.To.Add(new MailboxAddress(toName, toEmailAddress));
            email.Subject = subject;

            var builder = new BodyBuilder();

            // Set the plain-text version of the message text
            builder.TextBody = menssage;

            // In order to reference selfie.jpg from the html text, we'll need to add it
            // to builder.LinkedResources and then use its Content-Id value in the img src.


            var image = builder.LinkedResources.Add(@"C:\transer\imagenes\firmaDigital.PNG");

            image.ContentId = MimeUtils.GenerateMessageId();

            // Set the html version of the message text
            builder.HtmlBody =

                /*string.Format(@"<leftr><img src=""cid:{0}""></left>
                 * <p>El contenido de este mensaje pertenece a TRANSER S.A. y puede ser información privilegiada y confidencial. Si Usted no es el destinatario real del mismo, por favor informe de ello a quien lo envía y destrúyalo en forma inmediata. Está prohibida su retención, grabación, utilización o divulgación con cualquier propósito. Este mensaje ha sido verificado con software antivirus, en consecuencia, TRANSER S.A. no se hace responsable por la presencia en el o en sus anexos de algún virus que pueda generar daños en los equipos o programas del destinatario.<br>
                 * <p>The content of this message belong to TRANSER S.A. and may be privileged and confidential information. If you are not the real recipient, please inform to sender and delete it immediately. The withholding, saving, use or release for any purpose of this message is restricted. This message has been checked with antivirus software; Accordingly, TRANSER S.A. is not liable for the presence of any virus in its attachments that causes or may cause damage to the recipient's equipment or software.<br>
                 * <p>www.transer.com.co<br>", image.ContentId);
                 *
                 *
                 */
                builder.HtmlBody = string.Format(@"<p>El contenido de este mensaje pertenece a TRANSER S.A. y puede ser información privilegiada y confidencial. <br>
                                                           <p>Si Usted no es el destinatario real del mismo, por favor informe de ello a quien lo envía y destrúyalo en <br>
                                                           <p>forma inmediata. Está prohibida su retención, grabación, utilización o divulgación con cualquier propósito.<br>
                                                           <p>Este mensaje ha sido verificado con software antivirus, en consecuencia, TRANSER S.A. no se hace responsable <br>
                                                           <p>por la presencia en el o en sus anexos de algún virus que pueda generar daños en los equipos o programas del <br>
            <p>destinatario.<br>
            <p>www.transer.com.co<br>
            <center><img src=""cid:{0}""></center>", image.ContentId);

            // We may also want to attach a calendar event for Monica's party...


            //builder.Attachments.Add(@"C:\transer\documentos\condorito.pdf");

            // Now we just need to set the message body and we're done
            email.Body = builder.ToMessageBody();


            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback =
                    (sender, certificate, certChainType, errors) => true;
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);

                await client.AuthenticateAsync("francisco.montoya.l", "@Jsd2@xr1").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
        // This method using the Google API to send emails
        public static void sendEmailLessThanZero(string emailErrorResult)
        {
            Console.WriteLine("Trying to send an Email because error with {0} has occurred", emailErrorResult);

            // Declaring the email addresses used in this method, have not entered the correct emails addresses as for security reason
            // In a live version of this method the email addresses will be held in a more secure model
            string         youremailName      = "EnterName";
            string         youremailAddress   = "*****@*****.**";
            string         sendToName         = "EnterNameSendingto";
            string         sendToEmailAddress = "*****@*****.**";
            UserCredential credential;

            // A JSON secret file needs to be be generated in the Google API Manager to allow for authentication
            string locationGoogleClientSecretFile = "Enter location of the JSON Google API client secret file";

            using (var stream = new FileStream(locationGoogleClientSecretFile, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                credPath   = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, new[] {
                    GmailService.Scope.MailGoogleCom,
                    GmailService.Scope.GmailCompose,
                    GmailService.Scope.GmailModify, GmailService.Scope.GmailSend
                },
                                                                         "user",
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;

                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "GmailService API .NET Quickstart",
                });

                // The below code builds the message body of the mail, builder.HtmlBody can be used to build a HTML email if needed
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(youremailName, youremailAddress));
                message.To.Add(new MailboxAddress(sendToName, sendToEmailAddress));

                message.Subject = "An error has occurred with the calculations";
                var      builder  = new BodyBuilder();
                DateTime dateTime = DateTime.Now;
                string   strDate  = dateTime.ToString("HH:MM:ss, dddd, MMMM d, yyyy");

                builder.TextBody = @"An error has occurred with " + emailErrorResult + " at the followinf date time " + strDate;
                var contentId = MimeUtils.GenerateMessageId();

                // The email needs to be encoded before sending via the Google API
                message.Body = builder.ToMessageBody();
                var rawMessage = "";
                using (var streem = new MemoryStream())
                {
                    message.WriteTo(streem);
                    rawMessage = Convert.ToBase64String(streem.GetBuffer(), 0,
                                                        (int)streem.Length)
                                 .Replace('+', '-')
                                 .Replace('/', '_')
                                 .Replace("=", "");
                }

                var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
                {
                    Raw = rawMessage
                };

                // Send the encoded email and wrap in a Try Catch encase the email send is not successfully sent and report an erro has occured
                try
                {
                    service.Users.Messages.Send(gmailMessage, sendToEmailAddress).Execute();
                }
                catch (Exception e)
                {
                    Console.WriteLine("There was a problem sending the email via the Google Api");
                }
            }
        }
Beispiel #29
0
        protected void btnSendMail_Click(object sender, EventArgs e)
        {
            lblInfo.Text = "";
            // TEST INVIO MAIL DA ARUBA
            try
            {
                #region send con Mailkit
                var message = new MimeMessage();

                message.From.Add(new MailboxAddress(tbMailFrom.Text.Trim(), tbMailFrom.Text.Trim()));
                message.To.Add(new MailboxAddress(tbMailTo.Text.Trim(), tbMailTo.Text.Trim()));
                message.Subject = tbSubject.Text.Trim();

                var builder = new BodyBuilder();

                //builder.TextBody = tbBody.Text.Trim();

                builder.Attachments.Add(@"C:\TEMP\web.config");
                builder.HtmlBody = "<H1>" + tbBody.Text.Trim() + "</H1>";

                message.Body = builder.ToMessageBody();
                //message.HtmlBody = builder.ToMessageBody();
                //message.HtmlBody = builder.HtmlBody;

                try
                {
                    var client = new MailKit.Net.Smtp.SmtpClient();

                    client.Connect(tbClient.Text.Trim(), Convert.ToInt32(tbPorta.Text.Trim()), Convert.ToBoolean(ddlSSL.SelectedValue));
                    client.Authenticate(tbUser.Text.Trim(), tbPassword.Text.Trim());
                    client.Send(message);
                    client.Disconnect(true);

                    lblInfo.ForeColor = System.Drawing.Color.Green;
                    lblInfo.Text      = "Mail Inviata";
                }
                catch (Exception ex)
                {
                    lblInfo.ForeColor = System.Drawing.Color.Red;
                    lblInfo.Text      = "Errore invio mail" + Environment.NewLine + ex.Message;
                }

                #endregion

                #region send con Classi Net
                //MailMessage mail = new MailMessage();

                //string smtpClient = tbClient.Text.Trim();
                //// SERVER SMTP
                //SmtpClient SmtpServer = new SmtpClient(smtpClient);

                //// MITTENTE
                //mail.From = new MailAddress(tbMailFrom.Text.Trim());

                //// DESTINATARIO

                //char[] divisore = { ';' };
                //string[] arDestinatari = tbMailTo.Text.Trim().Split(divisore,StringSplitOptions.RemoveEmptyEntries);
                //foreach (string item in arDestinatari)
                //{
                //    mail.To.Add(item);
                //}

                //// OGGETTO MAIL
                //mail.Subject = tbSubject.Text.Trim();

                //// BODY MAIL
                //string body = tbBody.Text.Trim();

                //mail.Body = body;

                //string smtpServerCredentialsId = tbUser.Text.Trim();
                //string smtpServerCredentialsPassWord = tbPassword.Text.Trim();

                //// CREDENZIALI SERVER
                ////SmtpServer.Port = Convert.ToInt32(smtpServerPort);
                //SmtpServer.Port = Convert.ToInt32(tbPorta.Text.Trim());
                //SmtpServer.Credentials = new System.Net.NetworkCredential(smtpServerCredentialsId, smtpServerCredentialsPassWord);
                //SmtpServer.EnableSsl = Convert.ToBoolean(ddlSSL.SelectedValue);

                ////INVIO EMAIL
                //SmtpServer.Send(mail);

                //lblInfo.ForeColor = System.Drawing.Color.Green;
                //lblInfo.Text = "Mail Inviata";
                //// FINE TEST INVIO EMAIL
                # endregion
            }
            catch (Exception ex)
            {
                lblInfo.ForeColor = System.Drawing.Color.Red;
                lblInfo.Text      = "Errore invio mail" + Environment.NewLine + ex.Message;
            }
        }
Beispiel #30
0
        public async Task SendDonationEmail(Donate donateData, bool isForGoodsItem)
        {
            try
            {
                //From Address
                string FromAddress     = "*****@*****.**";
                string FromAdressTitle = "Email from Second Family";
                //To Address
                string ToAddress     = donateData.Email;
                string ToAdressTitle = "Second Family";
                string Subject       = "";
                string BodyContent   = "";
                if (isForGoodsItem)
                {
                    BodyContent += @"Hey " + donateData.FirstName + " " + donateData.LastName + ".";
                    BodyContent += "Thanks for your Donation of Goods & Items.<br /><br />";
                    BodyContent += "Item - " + donateData.Item + ".<br />";
                    BodyContent += "Quantity - " + donateData.Quantity + ".<br />";
                    BodyContent += "Location - " + donateData.Address + ".<br />";
                    if (!string.IsNullOrEmpty(donateData.PhoneNumber))
                    {
                        BodyContent += "PhoneNumber - " + donateData.PhoneNumber + ".<br />";
                    }
                    BodyContent += "Do you need a pickup? - " + donateData.NeedPickup + ".<br />";
                    BodyContent += "Can you drop off? - " + donateData.CanDropOff + ".<br />";
                    BodyContent += "Available date/time for pickup/drop off :- " + donateData.DatePickDrop + ".<br /><br /><br />";
                    BodyContent += "Thank You";
                    Subject      = "Donate Goods & Items";
                }
                else
                {
                    BodyContent += @"Dear " + donateData.FirstName + " " + donateData.LastName + ".";
                    BodyContent += "Your Donation Was Successfull !Thank you for Your Support to Second families!<br /><br />";
                    Subject      = "Donation";
                }
                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Cc.Add(new MailboxAddress("Haidari Hammad", "*****@*****.**"));
                mimeMessage.Bcc.Add(new MailboxAddress("Haidari Hammad", "*****@*****.**"));
                mimeMessage.Subject = Subject;

                var builder = new BodyBuilder();
                builder.HtmlBody = BodyContent;
                foreach (string file in Directory.EnumerateFiles(
                             env.WebRootPath + "\\dimage\\",
                             "*",
                             SearchOption.AllDirectories)
                         )
                {
                    builder.Attachments.Add(file);
                }
                mimeMessage.Body = builder.ToMessageBody();
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(SmtpServer, SmtpPortNumber, false).ConfigureAwait(false);

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    await client.AuthenticateAsync("*****@*****.**", "foodc@619619")
                    .ConfigureAwait(false);

                    await client.SendAsync(mimeMessage).ConfigureAwait(false);

                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #31
0
		static void ExtractMapiProperties (TnefReader reader, MimeMessage message, BodyBuilder builder)
		{
			var prop = reader.TnefPropertyReader;

			while (prop.ReadNextProperty ()) {
				switch (prop.PropertyTag.Id) {
				case TnefPropertyId.InternetMessageId:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
						message.MessageId = prop.ReadValueAsString ();
					}
					break;
				case TnefPropertyId.Subject:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
						message.Subject = prop.ReadValueAsString ();
					}
					break;
				case TnefPropertyId.RtfCompressed:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var rtf = new TextPart ("rtf");
						rtf.ContentType.Name = "body.rtf";

						var converter = new RtfCompressedToRtf ();
						var content = new MemoryStream ();

						using (var filtered = new FilteredStream (content)) {
							filtered.Add (converter);

							using (var compressed = prop.GetRawValueReadStream ()) {
								compressed.CopyTo (filtered, 4096);
								filtered.Flush ();
							}
						}

						rtf.ContentObject = new ContentObject (content);
						content.Position = 0;

						builder.Attachments.Add (rtf);
					}
					break;
				case TnefPropertyId.BodyHtml:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var html = new TextPart ("html");
						html.ContentType.Name = "body.html";
						html.Text = prop.ReadValueAsString ();

						builder.Attachments.Add (html);
					}
					break;
				case TnefPropertyId.Body:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var plain = new TextPart ("plain");
						plain.ContentType.Name = "body.txt";
						plain.Text = prop.ReadValueAsString ();

						builder.Attachments.Add (plain);
					}
					break;
				}
			}
		}
Beispiel #32
0
        public void RunJob()
        {
            using (var smtpClient = GetSmtpClient())
            {
                CoreContext.TenantManager.SetCurrentTenant(_tenantID);
                SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(_currUser));

                var userCulture = CoreContext.UserManager.GetUsers(_currUser).GetCulture();

                Thread.CurrentThread.CurrentCulture   = userCulture;
                Thread.CurrentThread.CurrentUICulture = userCulture;

                var contactCount = _contactID.Count;

                if (contactCount == 0)
                {
                    Complete();
                    return;
                }

                MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                var from      = new MailboxAddress(_smtpSetting.SenderDisplayName, _smtpSetting.SenderEmailAddress);
                var filePaths = new List <string>();
                using (var fileDao = FilesIntegration.GetFileDao())
                {
                    foreach (var fileID in _fileID)
                    {
                        var fileObj = fileDao.GetFile(fileID);
                        if (fileObj == null)
                        {
                            continue;
                        }
                        using (var fileStream = fileDao.GetFileStream(fileObj))
                        {
                            var directoryPath = Path.Combine(Path.GetTempPath(), "teamlab", _tenantID.ToString(),
                                                             "crm/files/mailsender/");
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            var filePath = Path.Combine(directoryPath, fileObj.Title);
                            using (var newFileStream = File.Create(filePath))
                            {
                                fileStream.StreamCopyTo(newFileStream);
                            }
                            filePaths.Add(filePath);
                        }
                    }
                }

                var templateManager = new MailTemplateManager(_daoFactory);
                var deliveryCount   = 0;

                try
                {
                    Error = string.Empty;
                    foreach (var contactID in _contactID)
                    {
                        if (IsCompleted)
                        {
                            break;              // User selected cancel
                        }
                        var contactInfoDao = _daoFactory.GetContactInfoDao();
                        var startDate      = DateTime.Now;

                        var contactEmails = contactInfoDao.GetList(contactID, ContactInfoType.Email, null, true);
                        if (contactEmails.Count == 0)
                        {
                            continue;
                        }

                        var recipientEmail = contactEmails[0].Data;

                        if (!recipientEmail.TestEmailRegex())
                        {
                            Error += string.Format(CRMCommonResource.MailSender_InvalidEmail, recipientEmail) + "<br/>";
                            continue;
                        }

                        var to = new MailboxAddress(recipientEmail);

                        var mimeMessage = new MimeMessage
                        {
                            Subject = _subject
                        };

                        mimeMessage.From.Add(from);
                        mimeMessage.To.Add(to);

                        var bodyBuilder = new BodyBuilder
                        {
                            HtmlBody = templateManager.Apply(_bodyTempate, contactID)
                        };

                        foreach (var filePath in filePaths)
                        {
                            bodyBuilder.Attachments.Add(filePath);
                        }

                        mimeMessage.Body = bodyBuilder.ToMessageBody();

                        mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                        _log.Debug(GetLoggerRow(mimeMessage));

                        var success = false;

                        try
                        {
                            smtpClient.Send(mimeMessage);

                            success = true;
                        }
                        catch (SmtpCommandException ex)
                        {
                            _log.Error(Error, ex);

                            if (ex.ErrorCode == SmtpErrorCode.RecipientNotAccepted)
                            {
                                if (ex.StatusCode == SmtpStatusCode.MailboxBusy ||
                                    ex.StatusCode == SmtpStatusCode.MailboxUnavailable)
                                {
                                    Error = string.Format(CRMCommonResource.MailSender_MailboxBusyException, 5);

                                    Thread.Sleep(TimeSpan.FromSeconds(5));

                                    smtpClient.Send(mimeMessage);

                                    success = true;
                                }
                                else
                                {
                                    Error +=
                                        string.Format(CRMCommonResource.MailSender_FailedDeliverException,
                                                      ex.Mailbox.Address) + "<br/>";
                                }
                            }
                        }

                        if (success)
                        {
                            if (_storeInHistory)
                            {
                                AddToHistory(contactID,
                                             string.Format(CRMCommonResource.MailHistoryEventTemplate, mimeMessage.Subject));
                            }

                            var endDate      = DateTime.Now;
                            var waitInterval = endDate.Subtract(startDate);

                            deliveryCount++;

                            var estimatedTime = TimeSpan.FromTicks(waitInterval.Ticks * (_contactID.Count - deliveryCount));

                            Status = new
                            {
                                RecipientCount = _contactID.Count,
                                EstimatedTime  = estimatedTime.ToString(),
                                DeliveryCount  = deliveryCount
                            };
                        }

                        _exactPercentageValue += 100.0 / contactCount;
                        Percentage             = Math.Round(_exactPercentageValue);

                        if (MailSenderDataCache.CheckCancelFlag())
                        {
                            MailSenderDataCache.ResetAll();

                            throw new OperationCanceledException();
                        }

                        MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());

                        if (Percentage > 100)
                        {
                            Percentage = 100;

                            if (MailSenderDataCache.CheckCancelFlag())
                            {
                                MailSenderDataCache.ResetAll();

                                throw new OperationCanceledException();
                            }

                            MailSenderDataCache.Insert((SendBatchEmailsOperation)Clone());
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    MailSenderDataCache.ResetAll();
                    _log.Debug("cancel mail sender");
                }
                finally
                {
                    MailSenderDataCache.ResetAll();

                    foreach (var filePath in filePaths)
                    {
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                Status = new
                {
                    RecipientCount = _contactID.Count,
                    EstimatedTime  = TimeSpan.Zero.ToString(),
                    DeliveryCount  = deliveryCount
                };
            }
            Complete();
        }
Beispiel #33
0
		static MimeMessage ExtractTnefMessage (TnefReader reader)
		{
			var builder = new BodyBuilder ();
			var message = new MimeMessage ();

			while (reader.ReadNextAttribute ()) {
				if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
					break;

				var prop = reader.TnefPropertyReader;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.RecipientTable:
					ExtractRecipientTable (reader, message);
					break;
				case TnefAttributeTag.MapiProperties:
					ExtractMapiProperties (reader, message, builder);
					break;
				case TnefAttributeTag.DateSent:
					message.Date = prop.ReadValueAsDateTime ();
					break;
				case TnefAttributeTag.Body:
					builder.TextBody = prop.ReadValueAsString ();
					break;
				}
			}

			if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
				ExtractAttachments (reader, builder);

			message.Body = builder.ToMessageBody ();

			return message;
		}
Beispiel #34
0
		static void ExtractAttachments (TnefReader reader, BodyBuilder builder)
		{
			var attachMethod = TnefAttachMethod.ByValue;
			var filter = new BestEncodingFilter ();
			var prop = reader.TnefPropertyReader;
			MimePart attachment = null;
			int outIndex, outLength;
			TnefAttachFlags flags;
			string[] mimeType;
			byte[] attachData;
			string text;

			do {
				if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
					break;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.AttachRenderData:
					attachMethod = TnefAttachMethod.ByValue;
					attachment = new MimePart ();
					break;
				case TnefAttributeTag.Attachment:
					if (attachment == null)
						break;

					while (prop.ReadNextProperty ()) {
						switch (prop.PropertyTag.Id) {
						case TnefPropertyId.AttachLongFilename:
							attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachFilename:
							if (attachment.FileName == null)
								attachment.FileName = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachContentLocation:
							text = prop.ReadValueAsString ();
							if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
								attachment.ContentLocation = new Uri (text, UriKind.Absolute);
							else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
								attachment.ContentLocation = new Uri (text, UriKind.Relative);
							break;
						case TnefPropertyId.AttachContentBase:
							text = prop.ReadValueAsString ();
							attachment.ContentBase = new Uri (text, UriKind.Absolute);
							break;
						case TnefPropertyId.AttachContentId:
							attachment.ContentId = prop.ReadValueAsString ();
							break;
						case TnefPropertyId.AttachDisposition:
							text = prop.ReadValueAsString ();
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition (text);
							else
								attachment.ContentDisposition.Disposition = text;
							break;
						case TnefPropertyId.AttachData:
							var stream = prop.GetRawValueReadStream ();
							var content = new MemoryStream ();
							var guid = new byte[16];

							if (attachMethod == TnefAttachMethod.EmbeddedMessage) {
								var tnef = new TnefPart ();

								foreach (var param in attachment.ContentType.Parameters)
									tnef.ContentType.Parameters[param.Name] = param.Value;

								if (attachment.ContentDisposition != null)
									tnef.ContentDisposition = attachment.ContentDisposition;

								attachment = tnef;
							}

							// read the GUID
							stream.Read (guid, 0, 16);

							// the rest is content
							using (var filtered = new FilteredStream (content)) {
								filtered.Add (filter);
								stream.CopyTo (filtered, 4096);
								filtered.Flush ();
							}

							content.Position = 0;

							attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
							attachment.ContentObject = new ContentObject (content);
							filter.Reset ();

							builder.Attachments.Add (attachment);
							break;
						case TnefPropertyId.AttachMethod:
							attachMethod = (TnefAttachMethod) prop.ReadValueAsInt32 ();
							break;
						case TnefPropertyId.AttachMimeTag:
							mimeType = prop.ReadValueAsString ().Split ('/');
							if (mimeType.Length == 2) {
								attachment.ContentType.MediaType = mimeType[0].Trim ();
								attachment.ContentType.MediaSubtype = mimeType[1].Trim ();
							}
							break;
						case TnefPropertyId.AttachFlags:
							flags = (TnefAttachFlags) prop.ReadValueAsInt32 ();
							if ((flags & TnefAttachFlags.RenderedInBody) != 0) {
								if (attachment.ContentDisposition == null)
									attachment.ContentDisposition = new ContentDisposition (ContentDisposition.Inline);
								else
									attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
							}
							break;
						case TnefPropertyId.AttachSize:
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition ();

							attachment.ContentDisposition.Size = prop.ReadValueAsInt64 ();
							break;
						case TnefPropertyId.DisplayName:
							attachment.ContentType.Name = prop.ReadValueAsString ();
							break;
						}
					}
					break;
				case TnefAttributeTag.AttachCreateDate:
					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.CreationDate = prop.ReadValueAsDateTime ();
					}
					break;
				case TnefAttributeTag.AttachModifyDate:
					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.ModificationDate = prop.ReadValueAsDateTime ();
					}
					break;
				case TnefAttributeTag.AttachTitle:
					if (attachment != null && string.IsNullOrEmpty (attachment.FileName))
						attachment.FileName = prop.ReadValueAsString ();
					break;
				case TnefAttributeTag.AttachMetaFile:
					if (attachment == null)
						break;

					// TODO: what to do with the meta data?
					break;
				case TnefAttributeTag.AttachData:
					if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
						break;

					attachData = prop.ReadValueAsBytes ();
					filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
					attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.EightBit);
					attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
					filter.Reset ();

					builder.Attachments.Add (attachment);
					break;
				}
			} while (reader.ReadNextAttribute ());
		}