public ActionResult AddOrEdit(SmtpHost smtpHost)
        {
            //HostType hostType = new AlphasoftWebsiteContext().HostTypes.FirstOrDefault(x => x.HostTypeId== HostTypeId);
            var data = _iSmtpHostManager.AddOrEdit(smtpHost);

            return(Json(new { messageType = data.MessageType, message = data.ReturnMessage, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", _iSmtpHostManager.GetAllSmtpHost()) }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 2
0
        protected override void DoStart()
        {
            m_Smtp = new SmtpClient();

            if (DropFolder.IsNotNullOrWhiteSpace() && System.IO.Directory.Exists(DropFolder))
            {
                m_Smtp.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                m_Smtp.PickupDirectoryLocation = DropFolder;
            }
            else
            {
                if (SmtpHost.IsNullOrWhiteSpace())
                {
                    throw new WebException(StringConsts.MAILER_SINK_SMTP_IS_NOT_CONFIGURED_ERROR + "SmtpHost==null|empty|0");
                }


                m_Smtp.Host                  = this.SmtpHost;
                m_Smtp.Port                  = this.SmtpPort;
                m_Smtp.EnableSsl             = this.SmtpSSL;
                m_Smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                m_Smtp.UseDefaultCredentials = false;
                m_Smtp.Credentials           = new NetworkCredential(this.CredentialsID, this.CredentialsPassword);
            }
        }
Esempio n. 3
0
        protected override void Execute(CodeActivityContext context)
        {
            SmtpClient smtpClient = new SmtpClient();

            if (!string.IsNullOrEmpty(SmtpHost.Get(context)))
            {
                smtpClient.Host = SmtpHost.Get(context);
            }
            if (SmtpPort.Get(context).HasValue)
            {
                smtpClient.Port = SmtpPort.Get(context).Value;
            }
            if (!string.IsNullOrEmpty(Username.Get(context)))
            {
                smtpClient.Credentials = new System.Net.NetworkCredential(Username.Get(context), Password.Get(context));
            }
            smtpClient.EnableSsl = EnableSsl.Get(context);

            MailMessage mailMessage = new MailMessage();

            mailMessage.To.Add(To.Get(context));
            mailMessage.From       = new MailAddress(From.Get(context));
            mailMessage.Subject    = Subject.Get(context);
            mailMessage.Body       = Body.Get(context);
            mailMessage.IsBodyHtml = IsBodyHtml.Get(context);

            if (SendAsync.Get(context))
            {
                smtpClient.SendAsync(mailMessage, null);
            }
            else
            {
                smtpClient.Send(mailMessage);
            }
        }
Esempio n. 4
0
        public Message AddOrEdit(SmtpHost smtpHost)
        {
            var message = new Message();
            var ID      = smtpHost.SmtpHostId;
            int result  = _iSmtpHostRepository.AddOrEdit(smtpHost);

            try
            {
                if (result > 0)
                {
                    if (Convert.ToInt32(ID) > 0)
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Updated Successfully!");
                    }
                    else
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Successful!");
                    }
                }
                else
                {
                    message = Message.SetMessages.SetErrorMessage("Could not be submitted!");
                }
            }
            catch (Exception e)
            {
                message = Message.SetMessages.SetWarningMessage(e.Message.ToString());
            }

            return(message);
        }
        public void Setup()
        {
            var containerBuilder = new ContainerBuilder();

            const int    port     = 587;
            const string hostName = "localhost";

            var smtpHost = new SmtpHost();

            smtpHost.HostName = hostName;
            smtpHost.Password = "";
            smtpHost.Port     = port;
            smtpHost.Ssl      = true;
            smtpHost.Username = "";

            var simpleSmtpServer = SimpleSmtpServer.Start(port);


            var outlookMailClientSettingMock = new Mock <IMailClientSetting>();

            outlookMailClientSettingMock.Setup(options => options.Timeout).Returns(30);
            outlookMailClientSettingMock.Setup(options => options.DisplayName).Returns(OutlookDisplayName);
            outlookMailClientSettingMock.Setup(options => options.UniqueName).Returns(OutlookUniqueName);
            outlookMailClientSettingMock.Setup(options => options.MailHost).Returns(smtpHost);

            containerBuilder.RegisterInstance(outlookMailClientSettingMock.Object).AsImplementedInterfaces()
            .SingleInstance();
            containerBuilder.RegisterType <OutlookMailClient>().AsImplementedInterfaces().InstancePerLifetimeScope();
            containerBuilder.RegisterInstance(simpleSmtpServer)
            .SingleInstance();

            AutofacContainer = containerBuilder.Build();
        }
        public ActionResult AddOrEdit(int id = 0)
        {
            //ViewBag.HostTypeId=
            SmtpHost smtpHost = new SmtpHost();

            if (id != 0)
            {
                smtpHost = _iSmtpHostManager.GetASmtpHost(id);
            }
            return(View(smtpHost));
        }
        /// <summary>
        /// Returns true if ComDayCqMailerDefaultMailServiceProperties instances are equal
        /// </summary>
        /// <param name="other">Instance of ComDayCqMailerDefaultMailServiceProperties to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(ComDayCqMailerDefaultMailServiceProperties other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     SmtpHost == other.SmtpHost ||
                     SmtpHost != null &&
                     SmtpHost.Equals(other.SmtpHost)
                     ) &&
                 (
                     SmtpPort == other.SmtpPort ||
                     SmtpPort != null &&
                     SmtpPort.Equals(other.SmtpPort)
                 ) &&
                 (
                     SmtpUser == other.SmtpUser ||
                     SmtpUser != null &&
                     SmtpUser.Equals(other.SmtpUser)
                 ) &&
                 (
                     SmtpPassword == other.SmtpPassword ||
                     SmtpPassword != null &&
                     SmtpPassword.Equals(other.SmtpPassword)
                 ) &&
                 (
                     FromAddress == other.FromAddress ||
                     FromAddress != null &&
                     FromAddress.Equals(other.FromAddress)
                 ) &&
                 (
                     SmtpSsl == other.SmtpSsl ||
                     SmtpSsl != null &&
                     SmtpSsl.Equals(other.SmtpSsl)
                 ) &&
                 (
                     SmtpStarttls == other.SmtpStarttls ||
                     SmtpStarttls != null &&
                     SmtpStarttls.Equals(other.SmtpStarttls)
                 ) &&
                 (
                     DebugEmail == other.DebugEmail ||
                     DebugEmail != null &&
                     DebugEmail.Equals(other.DebugEmail)
                 ));
        }
Esempio n. 8
0
 /// <summary>
 ///  Returns the hashcode for this object.
 /// </summary>
 /// <returns></returns>
 /// <remarks>
 /// Excluding those properties which are not serialized:
 /// ClientCertificates, ServerCertificateValidationCallback, NetworkCredential, ProtocolLoggerDelegate
 /// </remarks>
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = MaxFailures;
         hashCode = (hashCode * 397) ^ RetryDelayTime;
         hashCode = (hashCode * 397) ^ (MailOutputDirectory != null ? MailOutputDirectory.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (SmtpHost != null ? SmtpHost.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ SmtpPort;
         hashCode = (hashCode * 397) ^ (ClientDomain != null ? ClientDomain.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (LocalEndPoint != null ? LocalEndPoint.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (int)MessageOutput;
         hashCode = (hashCode * 397) ^ (int)SslProtocols;
         hashCode = (hashCode * 397) ^ (int)SecureSocketOptions;
         hashCode = (hashCode * 397) ^ Timeout;
         hashCode = (hashCode * 397) ^ DelayBetweenMessages;
         return(hashCode);
     }
 }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (SmtpHost != null)
         {
             hashCode = hashCode * 59 + SmtpHost.GetHashCode();
         }
         if (SmtpPort != null)
         {
             hashCode = hashCode * 59 + SmtpPort.GetHashCode();
         }
         if (SmtpUser != null)
         {
             hashCode = hashCode * 59 + SmtpUser.GetHashCode();
         }
         if (SmtpPassword != null)
         {
             hashCode = hashCode * 59 + SmtpPassword.GetHashCode();
         }
         if (FromAddress != null)
         {
             hashCode = hashCode * 59 + FromAddress.GetHashCode();
         }
         if (SmtpSsl != null)
         {
             hashCode = hashCode * 59 + SmtpSsl.GetHashCode();
         }
         if (SmtpStarttls != null)
         {
             hashCode = hashCode * 59 + SmtpStarttls.GetHashCode();
         }
         if (DebugEmail != null)
         {
             hashCode = hashCode * 59 + DebugEmail.GetHashCode();
         }
         return(hashCode);
     }
 }
        public int AddOrEdit(SmtpHost smtpHost)
        {
            if (smtpHost.SmtpHostId == 0)
            {
                string password = new EncryptionDecryption().Encrypt(smtpHost.UserName, smtpHost.Password);
                smtpHost.Password = password;

                smtpHost.CreatedBy   = "Ayesha";
                smtpHost.CreatedDate = DateTime.Now;
                _dbContext.SmtpHosts.Add(smtpHost);
            }
            else
            {
                string password = new EncryptionDecryption().Encrypt(smtpHost.UserName, smtpHost.Password);
                smtpHost.Password = password;

                smtpHost.UpdatedBy               = "Ayesha";
                smtpHost.UpdatedDate             = DateTime.Now;
                _dbContext.Entry(smtpHost).State = EntityState.Modified;
            }

            return(_dbContext.SaveChanges());
        }
Esempio n. 11
0
        //TODO add support for other email providers

        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results     = new List <ValidationResult>();
            var hasProvider = false;

            if (!SendgridApiKey.IsNullOrWhiteSpace())
            {
                hasProvider = true;
            }

            if (!SmtpHost.IsNullOrWhiteSpace() && SmtpPort > 0 && !SmtpUsername.IsNullOrWhiteSpace() && !SmtpPassword.IsNullOrWhiteSpace())
            {
                hasProvider = true;
            }

            //TODO add support for other email providers

            if (!hasProvider)
            {
                results.Add(new ValidationResult($"At least one email providers is required. The field {nameof(SendgridApiKey)} or SMTP fields is required.",
                                                 new[] { nameof(SendgridApiKey), nameof(SmtpHost), nameof(SmtpPort), nameof(SmtpUsername), nameof(SmtpPassword) }));
            }
            return(results);
        }
Esempio n. 12
0
        public void Setup()
        {
            var containerBuilder = new ContainerBuilder();

            const int    port     = 587;
            const string hostName = "localhost";

            // Simple SMTP mail server.
            var simpleSmtpServer = SimpleSmtpServer.Start(port);

            var smtpHost = new SmtpHost();

            smtpHost.HostName = hostName;
            smtpHost.Password = "";
            smtpHost.Port     = port;
            smtpHost.Ssl      = true;
            smtpHost.Username = "";

            var outlookMailClientSettingMock = new Mock <IMailClientSetting>();

            outlookMailClientSettingMock.Setup(options => options.Timeout).Returns(30);
            outlookMailClientSettingMock.Setup(options => options.DisplayName).Returns(OutlookDisplayName);
            outlookMailClientSettingMock.Setup(options => options.UniqueName).Returns(OutlookUniqueName);
            outlookMailClientSettingMock.Setup(options => options.MailHost).Returns(smtpHost);

            containerBuilder
            .RegisterInstance(outlookMailClientSettingMock.Object)
            .AsImplementedInterfaces()
            .SingleInstance();

            containerBuilder
            .RegisterType <OutlookMailClient>()
            .AsImplementedInterfaces()
            .OnActivating(context =>
            {
                var mailClientSetting         = context.Context.Resolve <IMailClientSetting>();
                var moqOutlookMailClient      = new Mock <OutlookMailClient>(mailClientSetting);
                moqOutlookMailClient.CallBase = true;

                var moqSenderMailAddress = new Mock <IMailAddress>();
                moqSenderMailAddress.Setup(moqSender => moqSender.Address).Returns(ValidSenderAddress);
                moqSenderMailAddress.Setup(moqSender => moqSender.DisplayName).Returns(ValidSenderAddress);

                var moqMailContent = new Mock <IMailContent>();
                moqMailContent.Setup(template => template.Content).Returns(ValidMailContent);
                moqMailContent.Setup(template => template.Subject).Returns(ValidMailSubject);
                moqMailContent.Setup(template => template.IsHtml).Returns(IsMailHtml);

                moqOutlookMailClient
                .Setup(moqClient =>
                       moqClient.GetMailContentAsync(ValidMailTemplateName, It.IsAny <CancellationToken>()))
                .ReturnsAsync(moqMailContent.Object);

                moqOutlookMailClient
                .Setup(moqClient =>
                       moqClient.GetMailContentAsync(InvalidMailTemplateName, It.IsAny <CancellationToken>()))
                .ReturnsAsync(() => throw new Exception(InvalidMailTemplateExceptionMessage));

                moqOutlookMailClient
                .Setup(moqClient =>
                       moqClient.GetSenderAsync(ValidSenderKey, It.IsAny <CancellationToken>()))
                .ReturnsAsync(moqSenderMailAddress.Object);

                moqOutlookMailClient
                .Setup(moqClient =>
                       moqClient.GetSenderAsync(InvalidSenderKey, It.IsAny <CancellationToken>()))
                .ReturnsAsync(() => throw new Exception(InvalidSenderExceptionMessage));

                context.ReplaceInstance(moqOutlookMailClient.Object);
            })
            .InstancePerLifetimeScope();

            containerBuilder
            .RegisterInstance(simpleSmtpServer)
            .SingleInstance();

            AutofacContainer = containerBuilder.Build();
        }
 public BasicMailSender(SmtpHost host, Port port)
 {
     this.port = port;
     this.host = host;
 }
Esempio n. 14
0
        public bool SendMail()
        {
            //基础验证
            if (SendMailAddr.IsNullOrEmpty())
            {
                return(false);
            }
            if (!ToMail.IsEmail())
            {
                return(false);
            }
            if (SmtpHost.IsNullOrEmpty())
            {
                return(false);
            }
            MailMessage message     = new MailMessage();
            SmtpClient  mSmtpClient = new SmtpClient();

            mSmtpClient.Host = SmtpHost;
            mSmtpClient.Port = Port;
            mSmtpClient.UseDefaultCredentials = false;
            mSmtpClient.EnableSsl             = IsSSL;

            if (IsAuth)
            {
                NetworkCredential nc = new NetworkCredential(SendMailAddr, Password);
                mSmtpClient.Credentials = nc.GetCredential(mSmtpClient.Host, mSmtpClient.Port, "NTLM");
            }
            else
            {
                mSmtpClient.Credentials = new NetworkCredential(SendMailAddr, Password);
            }
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.None;
            mSmtpClient.DeliveryMethod          = SmtpDeliveryMethod.Network;
            try
            {
                //// 加载发件人地址
                if (!SendUserNickName.IsNullOrEmpty())
                {
                    MailAddress from = new MailAddress(SendMailAddr, SendUserNickName);
                    message.From   = from;
                    message.Sender = from;
                }
                else
                {
                    MailAddress from = new MailAddress(SendMailAddr);
                    message.From   = from;
                    message.Sender = from;
                }

                // 加载收件人地址
                message.To.Add(new MailAddress(ToMail));

                // 加载标题
                message.Subject         = Subject;
                message.SubjectEncoding = Encoding.UTF8;
                // 设置发送时间
                //message.setSentDate(new Date());

                // 设置抄送
                if (null != CcList)
                {
                    foreach (String ccMail in CcList)
                    {
                        if (ccMail.IsEmail())
                        {
                            message.CC.Add(new MailAddress(ccMail));
                        }
                    }
                }
                // 设置抄送
                if (null != BccList)
                {
                    foreach (String bccMail in BccList)
                    {
                        if (bccMail.IsEmail())
                        {
                            message.Bcc.Add(new MailAddress(bccMail));
                        }
                    }
                }
                //添加正文内容,判断是否为html格式

                message.Body         = Content;
                message.IsBodyHtml   = IsHtml;
                message.BodyEncoding = Encoding.UTF8;
                message.Priority     = MailPriority.Normal;

                // 添加附件
                if (null != AttrList)
                {
                    ContentDisposition disposition;
                    Attachment         data;
                    foreach (String filePath in AttrList)
                    {
                        if (!File.Exists(filePath))
                        {
                            continue;
                        }
                        data        = new Attachment(filePath, MediaTypeNames.Application.Octet);
                        disposition = data.ContentDisposition;
                        disposition.CreationDate     = File.GetCreationTime(filePath);
                        disposition.ModificationDate = File.GetLastWriteTime(filePath);
                        disposition.ReadDate         = File.GetLastAccessTime(filePath);
                        message.Attachments.Add(data);
                    }
                }
                // 把邮件发送出去
                mSmtpClient.Send(message);
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
        public ActionResult ViewAll(FormCollection formCollection, int NewsletterMailId, int SmtpHostId)
        {
            MailMessage mailMessage = new MailMessage();

            SentMailLog sentMailLog = new SentMailLog();
            //List<SentMailLog> sentMailLogList= new List<SentMailLog>();
            //var newsLetterMailList = _iNewsletterMailManager.GetAllNewsletterMail().Select(x => new
            //{
            //    x.NewsletterMailId,
            //    x.Subject
            //}).ToList();

            //ViewBag.NewsletterMailId = new SelectList(newsLetterMailList, "NewsletterMailId", "Subject");
            NewsletterMail newsletterMail = _iNewsletterMailManager.GetANewsletterMail(NewsletterMailId);
            SmtpHost       smtpHost       = _iSmtpHostManager.GetASmtpHost(SmtpHostId);

            string[] ids = formCollection["NewsletterSubscriberId"].Split(new char[] { ',' });
            foreach (string id in ids)
            {
                var newsletterSubscriber = _iNewsletterSubscriberManager.GetANewsletterSubscriber(int.Parse(id));
                if (newsletterSubscriber.IsActive == true)
                {
                    mailMessage.To.Add(new MailAddress(newsletterSubscriber.NewsletterSubscriberEmail));

                    //mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
                    mailMessage.From       = new MailAddress(smtpHost.UserName);
                    mailMessage.Subject    = newsletterMail.Subject;
                    mailMessage.IsBodyHtml = true;
                    mailMessage.Body       = newsletterMail.Body;

                    var    allowedExtensions = new[] { ".GIF", ".PNG", ".JPG", ".JPEG" };
                    string myfile            = Path.GetFileName(newsletterMail.AttachFile);

                    var        path = ConfigurationManager.AppSettings["AttachFile"];
                    var        file = Path.Combine(Server.MapPath(path), myfile);
                    Attachment data = new Attachment(file);

                    ContentDisposition disposition = data.ContentDisposition;
                    disposition.CreationDate     = System.IO.File.GetCreationTime(file);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                    disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);

                    mailMessage.Attachments.Add(data);
                    //mailMessage.DeliveryNotificationOptions= DeliveryNotificationOptions.OnSuccess;
                    SmtpClient client = new SmtpClient();
                    //client.Host = ConfigurationManager.AppSettings["Host"];
                    client.Host = smtpHost.HostType.HostName;
                    //client.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
                    client.EnableSsl = smtpHost.HostType.EnableSsl;
                    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                    //NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
                    NetworkCred.UserName = smtpHost.UserName;
                    //NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
                    NetworkCred.Password = smtpHost.Password;
                    //string encryptedPassword = smtpHost.Password;
                    //string password = new EncryptionDecryption().Decrypt(smtpHost.UserName, encryptedPassword);

                    client.UseDefaultCredentials = true;
                    client.Credentials           = NetworkCred;
                    //client.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
                    client.Port = int.Parse(smtpHost.HostType.PortNumber);


                    try
                    {
                        client.Send(mailMessage);
                        ViewBag.Result = "Mail Sent";
                        //if (ViewBag.Result==null)
                        //{
                        //    ViewBag.Result="Mail not sent" + newsletterSubscriber.NewsletterSubscriberEmail;
                        //}
                        sentMailLog.NewsletterSubscriberEmailId = newsletterSubscriber.NewsletterSubscriberEmail;
                        sentMailLog.NewsletterMailSubject       = newsletterMail.Subject;
                        sentMailLog.CreatedBy   = 1;
                        sentMailLog.CreatedDate = DateTime.Now;
                        sentMailLog.IsSent      = true;
                        AlphasoftWebsiteContext db = new AlphasoftWebsiteContext();
                        db.SentMailLogs.Add(sentMailLog);
                        db.SaveChanges();
                    }
                    catch (SmtpFailedRecipientException ex)
                    {
                        ViewBag.Result = ex.Message;
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="emailRecipientList">收件人</param>
        /// <param name="ccRecipientList">抄送人</param>
        /// <param name="title">标题</param>
        /// <param name="content">内容</param>
        /// <param name="attachmentPathList">邮件附件</param>
        /// <returns></returns>
        public bool SendMail(List <string> emailRecipientList, List <string> ccRecipientList, string title, string content, List <string> attachmentPathList)
        {
            MailMessage message  = new MailMessage();
            MailAddress fromAddr = new MailAddress(this.EmailAccount);

            message.From = fromAddr;
            foreach (string emailRecipient in emailRecipientList)
            {
                message.To.Add(emailRecipient.Trim());
            }
            if (ccRecipientList != null && ccRecipientList.Count > 0)
            {
                foreach (string ccRecipient in ccRecipientList)
                {
                    message.CC.Add(ccRecipient.Trim());
                }
            }

            //设置邮件标题
            message.Subject = title;
            //设置邮箱内容
            message.Body = content;
            //html
            message.IsBodyHtml = true;
            //设置邮件附件
            if (attachmentPathList != null && attachmentPathList.Count > 0)
            {
                foreach (var item in attachmentPathList)
                {
                    string SUpFile = item;
                    if (SUpFile != null && SUpFile != "")
                    {
                        //将文件进行转换成Attachments
                        Attachment data = new Attachment(SUpFile, MediaTypeNames.Application.Octet);;
                        //Add time stamp information for the file.
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.CreationDate     = System.IO.File.GetCreationTime(SUpFile);
                        disposition.ModificationDate = System.IO.File.GetLastWriteTime(SUpFile);
                        disposition.ReadDate         = System.IO.File.GetLastAccessTime(SUpFile);

                        message.Attachments.Add(data);
                    }
                }
            }

            //设置发送服务器,服务器根据你使用的邮箱而不用,可以到相应的邮箱管理后台查看
            if (SmtpHost == null || SmtpHost.Trim() == "")
            {
                SmtpHost = "smtp.qiye.163.com";
            }
            if (SmtpPort == null || SmtpPort == 0)
            {
                SmtpPort = 587;
            }

            SmtpClient client = new SmtpClient(SmtpHost, (int)SmtpPort);

            //设置发送人的邮箱账户和密码
            client.Credentials = new NetworkCredential(EmailAccount, EmailPassword);
            //启动ssl,也就是安全发送
            client.EnableSsl = EnableSsl;

            try
            {
                client.Send(message);
                foreach (Attachment item in message.Attachments)
                {
                    item.Dispose();
                }
                message = null;
                GC.Collect();
                return(true);
            }
            catch (Exception ex)
            {
                message.Attachments.Clear();
                message = null;
                GC.Collect();
                Console.WriteLine(ex.ToString());
                return(false);
            }
        }
Esempio n. 17
0
        public async Task <bool> SendAsync(EmailMessage email, SmtpHost host, ICredentials credentials,
                                           bool deleteAttachmentes, params string[] attachments)
        {
            if (string.IsNullOrWhiteSpace(email.SentTo))
            {
                throw new ArgumentNullException(email.SentTo);
            }

            if (string.IsNullOrWhiteSpace(email.Message))
            {
                throw new ArgumentNullException(email.Message);
            }

            var addresses = email.SentTo.Split(',');

            foreach (var validator in addresses.Select(address => new Validator(address)))
            {
                validator.Validate();

                if (!validator.IsValid)
                {
                    return(false);
                }
            }

            addresses    = addresses.Distinct().ToArray();
            email.SentTo = string.Join(",", addresses);
            email.Status = Status.Executing;


            using (var mail = new MailMessage(email.FromEmail, email.SentTo))
            {
                if (attachments != null)
                {
                    foreach (string file in attachments)
                    {
                        if (!string.IsNullOrWhiteSpace(file))
                        {
                            if (File.Exists(file))
                            {
                                var attachment = new Attachment(file, MediaTypeNames.Application.Octet);

                                var disposition = attachment.ContentDisposition;
                                disposition.CreationDate     = File.GetCreationTime(file);
                                disposition.ModificationDate = File.GetLastWriteTime(file);
                                disposition.ReadDate         = File.GetLastAccessTime(file);

                                disposition.FileName        = Path.GetFileName(file);
                                disposition.Size            = new FileInfo(file).Length;
                                disposition.DispositionType = DispositionTypeNames.Attachment;

                                mail.Attachments.Add(attachment);
                            }
                        }
                    }
                }


                var sender = new MailAddress(email.FromEmail, email.FromName);
                using (var smtp = new SmtpClient(host.Address, host.Port))
                {
                    smtp.DeliveryMethod          = host.DeliveryMethod;
                    smtp.PickupDirectoryLocation = host.PickupDirectory;

                    smtp.EnableSsl             = host.EnableSsl;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials           = new NetworkCredential(credentials.Username, credentials.Password);
                    try
                    {
                        mail.Subject    = email.Subject;
                        mail.Body       = email.Message;
                        mail.IsBodyHtml = email.IsBodyHtml;

                        mail.SubjectEncoding = Encoding.UTF8;
                        email.Status         = Status.Completed;

                        mail.ReplyToList.Add(sender);

                        await smtp.SendMailAsync(mail);

                        return(true);
                    }
                    catch (SmtpException ex)
                    {
                        email.Status = Status.Failed;
                        Log.Warning(@"Could not send email to {To}. {Ex}. ", email.SentTo, ex);
                    }
                    finally
                    {
                        foreach (IDisposable item in mail.Attachments)
                        {
                            item?.Dispose();
                        }

                        if (deleteAttachmentes)
                        {
                            DeleteFiles(attachments);
                        }
                    }
                }
            }

            return(false);
        }
Esempio n. 18
0
        public static MailHost GetPop3Host(SmtpHost smtphost)
        {
            MailHost host = new MailHost();

            switch (smtphost)
            {
            case SmtpHost.qq:
                host.mailHost = "pop.qq.com";
                host.mailPort = 110;
                break;

            case SmtpHost.qqexmail:
                host.mailHost = "pop.exmail.qq.com";
                host.mailPort = 995;
                break;

            case SmtpHost.wy126:
                host.mailHost = "pop.126.com";
                host.mailPort = 110;
                break;

            case SmtpHost.wy163:
                host.mailHost = "pop.126.com";
                host.mailPort = 110;
                break;

            case SmtpHost.china:
                host.mailHost = "pop.china.com";
                host.mailPort = 110;
                break;

            case SmtpHost.HotMail:
                host.mailHost = "pop.live.com";
                host.mailPort = 995;
                break;

            case SmtpHost.yd139:
                host.mailHost = "POP.139.com";
                host.mailPort = 110;
                break;

            case SmtpHost.gmail:
                host.mailHost = "pop.gmail.com";
                host.mailPort = 995;
                break;

            case SmtpHost.els263cn:
                host.mailHost = "pop.263.net.cn";
                host.mailPort = 110;
                break;

            case SmtpHost.dx21cn:
                host.mailHost = "pop.21cn.com";
                host.mailPort = 110;
                break;

            case SmtpHost.Foxmail:
                host.mailHost = "POP.foxmail.com";
                host.mailPort = 110;
                break;

            case SmtpHost.sina:
                host.mailHost = "pop3.sina.com.cn";
                host.mailPort = 110;
                break;

            case SmtpHost.sinaVIP:
                host.mailHost = "pop3.vip.sina.com";
                host.mailPort = 110;
                break;

            case SmtpHost.tom:
                host.mailHost = "pop.tom.com";
                host.mailPort = 110;
                break;

            case SmtpHost.sohu:
                host.mailHost = "pop3.sohu.com";
                host.mailPort = 110;
                break;

            case SmtpHost.etang:
                host.mailHost = "smtp.etang.com";
                host.mailPort = 110;
                break;

            case SmtpHost.els263:
                host.mailHost = "pop3.263.net";
                host.mailPort = 110;
                break;

            case SmtpHost.x263:
                host.mailHost = "pop.x263.net";
                host.mailPort = 110;
                break;

            case SmtpHost.yahoo:
                host.mailHost = "pop.mail.yahoo.com";
                host.mailPort = 110;
                break;

            case SmtpHost.yahooISSSL:
                host.mailHost = "pop.mail.yahoo.com";
                host.mailPort = 995;
                break;

            case SmtpHost.yahoocn:
                host.mailHost = "pop.mail.yahoo.com.cn";
                host.mailPort = 995;
                break;
            }
            return(host);
        }
Esempio n. 19
0
 public static SmtpClient GetClient(SmtpHost smtpHost)
 {
     return(new SmtpClient(smtpHost.HostName, smtpHost.Port));
 }