protected SmtpException (SerializationInfo info, StreamingContext context)
			: base (info, context)
		{
			try {
				statusCode = (SmtpStatusCode) info.GetValue ("Status", typeof (int));
			} catch (SerializationException) {
				//For compliance with previously serialized version:
				statusCode = (SmtpStatusCode) info.GetValue ("statusCode", typeof (SmtpStatusCode));
			}
		}
        static string GetMessageForStatus(SmtpStatusCode statusCode)
        {
            switch (statusCode)
            {
                default :
                case SmtpStatusCode.CommandUnrecognized:
                    return SR.GetString(SR.SmtpCommandUnrecognized);
                case SmtpStatusCode.SyntaxError:
                    return SR.GetString(SR.SmtpSyntaxError);
                case SmtpStatusCode.CommandNotImplemented:
                    return SR.GetString(SR.SmtpCommandNotImplemented);
                case SmtpStatusCode.BadCommandSequence:
                    return SR.GetString(SR.SmtpBadCommandSequence);
                case SmtpStatusCode.CommandParameterNotImplemented:
                    return SR.GetString(SR.SmtpCommandParameterNotImplemented);
                case SmtpStatusCode.SystemStatus:
                    return SR.GetString(SR.SmtpSystemStatus);
                case SmtpStatusCode.HelpMessage:
                    return SR.GetString(SR.SmtpHelpMessage);
                case SmtpStatusCode.ServiceReady:
                    return SR.GetString(SR.SmtpServiceReady);
                case SmtpStatusCode.ServiceClosingTransmissionChannel:
                    return SR.GetString(SR.SmtpServiceClosingTransmissionChannel);
                case SmtpStatusCode.ServiceNotAvailable:
                    return SR.GetString(SR.SmtpServiceNotAvailable);
                case SmtpStatusCode.Ok:
                    return SR.GetString(SR.SmtpOK);
                case SmtpStatusCode.UserNotLocalWillForward:
                    return SR.GetString(SR.SmtpUserNotLocalWillForward);
                case SmtpStatusCode.MailboxBusy:
                    return SR.GetString(SR.SmtpMailboxBusy);
                case SmtpStatusCode.MailboxUnavailable:
                    return SR.GetString(SR.SmtpMailboxUnavailable);
                case SmtpStatusCode.LocalErrorInProcessing:
                    return SR.GetString(SR.SmtpLocalErrorInProcessing);
                case SmtpStatusCode.UserNotLocalTryAlternatePath:
                    return SR.GetString(SR.SmtpUserNotLocalTryAlternatePath);
                case SmtpStatusCode.InsufficientStorage:
                    return SR.GetString(SR.SmtpInsufficientStorage);
                case SmtpStatusCode.ExceededStorageAllocation:
                    return SR.GetString(SR.SmtpExceededStorageAllocation);
                case SmtpStatusCode.MailboxNameNotAllowed:
                    return SR.GetString(SR.SmtpMailboxNameNotAllowed);
                case SmtpStatusCode.StartMailInput:
                    return SR.GetString(SR.SmtpStartMailInput);
                case SmtpStatusCode.TransactionFailed:
                    return SR.GetString(SR.SmtpTransactionFailed);
                case SmtpStatusCode.ClientNotPermitted:
                    return SR.GetString(SR.SmtpClientNotPermitted);
                case SmtpStatusCode.MustIssueStartTlsFirst:
                    return SR.GetString(SR.SmtpMustIssueStartTlsFirst);

            }
        }
 private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
 {
     if (statusCode != SmtpStatusCode.Ok)
     {
         if (statusCode < ((SmtpStatusCode) 400))
         {
             throw new SmtpException(SR.GetString("net_webstatus_ServerProtocolViolation"), serverResponse);
         }
         throw new SmtpException(statusCode, serverResponse, true);
     }
 }
 private static void CheckResponse(SmtpStatusCode statusCode, string response)
 {
     switch (statusCode)
     {
         case SmtpStatusCode.Ok:
             return;
     }
     if (statusCode < ((SmtpStatusCode) 400))
     {
         throw new SmtpException(SR.GetString("net_webstatus_ServerProtocolViolation"), response);
     }
     throw new SmtpException(statusCode, response, true);
 }
        public bool CheckMailboxExists(string email, out SmtpStatusCode result)
        {
            try
            {
                using (TcpClient tcpClient = new TcpClient())
                {
                    tcpClient.SendTimeout = 1000;
                    tcpClient.ReceiveTimeout = 1000;

                    if (!tcpClient.ConnectAsync(this.host, this.port).Wait(1000))
                    {
                        throw new SmtpClientTimeoutException();
                    }

                    NetworkStream networkStream = tcpClient.GetStream();
                    StreamReader streamReader = new StreamReader(networkStream);

                    this.AcceptResponse(streamReader, SmtpStatusCode.ServiceReady);

                    string mailHost = (new MailAddress(email)).Host;

                    this.SendCommand(networkStream, streamReader, "HELO " + mailHost, SmtpStatusCode.Ok);
                    this.SendCommand(networkStream, streamReader, "MAIL FROM:<check@" + mailHost + ">", SmtpStatusCode.Ok);
                    SmtpResponse response = this.SendCommand(networkStream, streamReader, "RCPT TO:<" + email + ">");
                    this.SendCommand(networkStream, streamReader, "QUIT", SmtpStatusCode.ServiceClosingTransmissionChannel, SmtpStatusCode.MailboxUnavailable);

                    result = response.Code;

                    return true;
                }
            }
            catch (IOException e)
            {
                // StreamReader problem
            }
            catch (SocketException e)
            {
                // TcpClient problem
            }

            result = SmtpStatusCode.GeneralFailure;
            return false;
        }
        private static bool CheckResponse(SmtpStatusCode statusCode, string response)
        {
            switch (statusCode)
            {
                case SmtpStatusCode.Ok:
                case SmtpStatusCode.UserNotLocalWillForward:
                    return true;

                case SmtpStatusCode.MailboxBusy:
                case SmtpStatusCode.InsufficientStorage:
                case SmtpStatusCode.MailboxUnavailable:
                case SmtpStatusCode.UserNotLocalTryAlternatePath:
                case SmtpStatusCode.ExceededStorageAllocation:
                case SmtpStatusCode.MailboxNameNotAllowed:
                    return false;
            }
            if (statusCode < ((SmtpStatusCode) 400))
            {
                throw new SmtpException(SR.GetString("net_webstatus_ServerProtocolViolation"), response);
            }
            throw new SmtpException(statusCode, response, true);
        }
示例#7
0
        private static void CheckResponse(SmtpStatusCode statusCode, string response)
        {
            switch (statusCode)
            {
                case SmtpStatusCode.Ok:
                    {
                        return;
                    }
                case SmtpStatusCode.ExceededStorageAllocation:
                case SmtpStatusCode.LocalErrorInProcessing:
                case SmtpStatusCode.InsufficientStorage:
                default:
                    {
                        if ((int)statusCode < 400)
                        {
                            throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, response);
                        }

                        throw new SmtpException(statusCode, response, true);
                    }
            }
        }
 internal LineInfo(SmtpStatusCode statusCode, string line)
 {
     this.statusCode = statusCode;
     this.line = line;
 }
示例#9
0
        private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
        {
            switch (statusCode)
            {
                case SmtpStatusCode.Ok:
                    {
                        return;
                    }
                default:
                    {
                        if ((int)statusCode < 400)
                        {
                            throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, serverResponse);
                        }

                        throw new SmtpException(statusCode, serverResponse, true);
                    }
            }
        }
		public SmtpFailedRecipientException (SmtpStatusCode statusCode, string failedRecipient) : base (statusCode)
		{
			this.failedRecipient = failedRecipient;
		}
示例#11
0
        public IActionResult SendMail(Email email)
        {
            var builder       = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
            var configuration = builder.Build();

            string ServidorSMTP         = string.Empty;
            int    PuertoServidorSMTP   = 0;
            string RemitenteMail        = string.Empty;
            string DisplayNameRemitente = string.Empty;
            string PassMailRemitente    = string.Empty;
            bool   Ssl = false;

            ServidorSMTP         = configuration["ServidorSMTP"];
            PuertoServidorSMTP   = int.Parse(configuration["PuertoServidorSMTP"]);
            RemitenteMail        = configuration["RemitenteMail"];
            DisplayNameRemitente = configuration["DisplayNameRemitente"];
            PassMailRemitente    = configuration["PassMailRemitente"];
            Ssl = bool.Parse(configuration["Ssl"]);

            SmtpClient smtpClient = new SmtpClient(ServidorSMTP, PuertoServidorSMTP)
            {
                UseDefaultCredentials = false,
                Credentials           = new System.Net.NetworkCredential(RemitenteMail, PassMailRemitente),
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                EnableSsl             = Ssl
            };

            MailMessage mail = new MailMessage();

            mail.IsBodyHtml = email.IsBodyHtml;
            mail.Body       = email.CuerpoMail;
            mail.Subject    = email.AsuntoMail;
            mail.From       = new MailAddress(RemitenteMail, DisplayNameRemitente);
            mail.To.Add(new MailAddress(email.Destinatario));

            try
            {
                smtpClient.Send(mail);

                Logger.LoggerMessage("Email API: 200 - Email has been send");
                return(StatusCode(200, "Email has been send"));
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy ||
                        status == SmtpStatusCode.MailboxUnavailable)
                    {
                        System.Threading.Thread.Sleep(5000);
                        smtpClient.Send(mail);
                        return(StatusCode(200, "Email has been send"));
                    }
                    else
                    {
                        Logger.LoggerMessage("Email API: 520 - " + status + " - " + ex.Message.ToString());
                        return(StatusCode(520, status + " - " + ex.Message.ToString()));
                    }
                }
                Logger.LoggerMessage("Email API: 520" + ex.Message.ToString());
                return(StatusCode(520, ex.Message.ToString()));
            }
            catch (SmtpException ex)
            {
                Logger.LoggerMessage("Email API: 520 - " + ex.Message.ToString());
                return(StatusCode(520, ex.Message.ToString()));
            }
            catch (Exception ex)
            {
                Logger.LoggerMessage("Email API: 520 - " + ex.Message.ToString());
                return(StatusCode(520, ex.Message.ToString()));
            }
        }
		public SmtpException (SmtpStatusCode statusCode, string message)
			: base (message)
		{
			this.statusCode = statusCode;
		}
 // Constructors
 public SmtpException(SmtpStatusCode statusCode)
 {
 }
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient, string serverResponse)
 {
 }
        public ResultContainer SendMessage(EmailMessage emailMessage)
        {
            StringBuilder sbResultDescription = new StringBuilder();
            MailAddress   from    = new MailAddress(emailMessage.From);
            MailMessage   message = new MailMessage();

            message.From = from;

            foreach (var emailAddress in emailMessage.Recipients)
            {
                message.To.Add(emailAddress);
            }
            message.ReplyToList.Add(new MailAddress(emailMessage.From));
            message.Subject    = emailMessage.Subject;
            message.Body       = emailMessage.Body;
            message.IsBodyHtml = true;

            // CONSIDER FOR LATER RELEASE
            //MailAddress copy = new MailAddress("*****@*****.**");
            //message.CC.Add(copy);
            if (!String.IsNullOrEmpty(emailMessage.BCC))
            {
                string[] bccList = emailMessage.BCC.Split(',');
                foreach (var bccEmail in bccList)
                {
                    message.Bcc.Add(bccEmail);
                }
            }

            SmtpClient client = new SmtpClient(SMTP_SERVER);

            //NEEDED?
            //client.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;

            ResultContainer resultContainer = new ResultContainer();

            resultContainer.ResultCode = ResultContainer.ResultCodeValue.OK.ToString();

            try
            {
                client.Send(message);
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy ||
                        status == SmtpStatusCode.MailboxUnavailable)
                    {
                        sbResultDescription.Append("Delivery failed - retrying in 5 seconds.");
                        System.Threading.Thread.Sleep(5000);
                        client.Send(message);
                    }
                    else
                    {
                        sbResultDescription.Append(String.Format("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient));
                    }
                }
            }
            catch (SmtpFailedRecipientException smex)
            {
                resultContainer.ResultCode    = ResultContainer.ResultCodeValue.Error.ToString();
                resultContainer.ResultMessage = smex.Message;
            }
            catch (Exception ex)
            {
                resultContainer.ResultCode    = ResultContainer.ResultCodeValue.Error.ToString();
                resultContainer.ResultMessage = String.Format("Exception caught in RetryIfBusy(): {0}", ex.ToString());
            }
            return(resultContainer);
        }
示例#16
0
        public async Task <ActionResult> CreateActivite(EventsModel eventsModel, int?id, int?idgroupe, bool GAC)
        {
            Activites activites = new Activites();

            activites.Nom_activ       = eventsModel.Title;
            activites.Objectif_activ  = eventsModel.Description;
            activites.Type_ActiviteID = eventsModel.Type_ActiviteID;
            activites.Emplacement     = eventsModel.Location;
            activites.AgendaID        = eventsModel.AgendaId;
            activites.DateStart       = eventsModel.DateStart;
            activites.DateEnd         = eventsModel.DateEnd;
            activites.statu           = false;
            db.Activites.Add(activites);
            try
            {
                await db.SaveChangesAsync();
            }catch (DbEntityValidationException DbExc)
            {
                string error = "";
                foreach (var er in DbExc.EntityValidationErrors)
                {
                    foreach (var ve in er.ValidationErrors)
                    {
                        error += " - " + ve.ErrorMessage;
                    }
                }
                TempData["Message"] = error;
            }

            IList <EventAttendee> AttList = new List <EventAttendee>();

            var          MemL         = db.Membre_group.Where(mg => mg.GroupId == idgroupe);
            Membre_group membre_Group = new Membre_group();

            foreach (var item in MemL)
            {
                EventAttendee eventAttendee = new EventAttendee();
                eventAttendee.Email = item.Utilisateur.Email;
                AttList.Add(eventAttendee);
                //new EventAttendee() { Email = item.Utilisateur.Email };
            }
            ///// Email Send //////////////////////////////
            GetMailData();
            EMail   mail        = new EMail();
            dynamic MailMessage = new MailMessage();

            MailMessage.From = new MailAddress(FromAddress);
            foreach (var item in MemL)
            {
                MailMessage.To.Add(item.Utilisateur.Email);
            }
            MailMessage.Subject    = "Espace MEFRA Notification";
            MailMessage.IsBodyHtml = true;
            MailMessage.Body       = "Nouveau Activité";


            SmtpClient SmtpClient = new SmtpClient();

            SmtpClient.Host        = strSmtpClient;
            SmtpClient.EnableSsl   = bEnableSSL;
            SmtpClient.Port        = Int32.Parse(SMTPPort);
            SmtpClient.Credentials = new System.Net.NetworkCredential(UserID, Password);

            try
            {
                try
                {
                    SmtpClient.Send(MailMessage);
                }
                catch (Exception ex)
                {
                }
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i <= ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.StatusCode;
                    if ((status == SmtpStatusCode.MailboxBusy) | (status == SmtpStatusCode.MailboxUnavailable))
                    {
                        System.Threading.Thread.Sleep(5000);
                        SmtpClient.Send(MailMessage);
                    }
                }
            }


            if (GAC)
            {
                UserCredential credential;
                using (var stream =
                           new FileStream(Path.Combine(Server.MapPath("~/Credentials"), "credentials-MinFin.json"), FileMode.Open, FileAccess.Read))
                {
                    // The file token.json stores the user's access and refresh tokens, and is created
                    // automatically when the authorization flow completes for the first time.
                    string credPath = Path.Combine(Server.MapPath("~/Credentials"), "token" + id + ".json");
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                }

                // Create Google Calendar API service.
                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });
                // Define parameters of request.
                EventsResource.ListRequest request = service.Events.List("primary");
                request.TimeMin      = DateTime.Now;
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.MaxResults   = 10;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;



                Event newEvent = new Event()
                {
                    Summary     = eventsModel.Title,
                    Location    = eventsModel.Location,
                    Description = eventsModel.Description,
                    Start       = new EventDateTime()
                    {
                        DateTime = DateTime.Parse(string.Format("{0:s}", eventsModel.DateStart)),
                        TimeZone = "Africa/Casablanca",
                    },
                    End = new EventDateTime()
                    {
                        DateTime = DateTime.Parse(string.Format("{0:s}", eventsModel.DateEnd)),
                        TimeZone = "Africa/Casablanca",
                    },
                    Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" },
                    Attendees  = AttList,
                    Reminders  = new Event.RemindersData()
                    {
                        UseDefault = false,
                        Overrides  = new EventReminder[] {
                            new EventReminder()
                            {
                                Method = "email", Minutes = 24 * 60
                            },
                            new EventReminder()
                            {
                                Method = "sms", Minutes = 10
                            },
                        }
                    }
                };

                EventsResource.InsertRequest request2 = service.Events.Insert(newEvent, eventsModel.GoogleCalendarID);

                request2.Execute();
            }

            ViewBag.Type_ActiviteID = new SelectList(db.Type_Activite, "ID", "Nom_type");
            ViewData["idagenda"]    = id;
            ViewData["idgroupe"]    = idgroupe;
            ViewData["GAC"]         = GAC;
            return(RedirectToAction("TestApi", "Agenda", new { id }));
        }
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient)
 {
 }
示例#18
0
        /// <summary>
        /// Sende Email an eine Empängerliste.
        /// </summary>
        /// <param name="toList">Empfängerliste</param>
        /// <param name="message">Inhalt der Email</param>
        /// <param name="subject">Betreff. Leer: Wird aus message generiert.</param>
        /// <param name="emailId">Id zur Protokollierung der Sendungsverfolgung in der Datenbank</param>
        /// <param name="sendCC">Sende an Ständige Empänger in CC</param>
        public static void Send(MailAddressCollection toList, string message, string subject = "", int emailId = 0, bool sendCC = true)
        {
            Console.WriteLine("Sende Email: " + message);

            if (emailId == 0)
            {
                emailId = (int)(DateTime.UtcNow.Ticks % int.MaxValue);
            }

            MailMessage mail = new MailMessage();

            try
            {
                #region From
                mail.From   = From;
                mail.Sender = From;
                #endregion

                #region To
                foreach (var to in toList ?? new MailAddressCollection()
                {
                    Admin
                })
                {
#if DEBUG           //nur zu mir
                    if (to.Address.ToLower() != Admin.Address.ToLower())
                    {
                        Console.WriteLine("Send(): Emailadresse gesperrt: " + to.Address);
                    }
                    else
#endif
                    mail.To.Add(to);
                }

                if (sendCC)
                {
                    foreach (var cc in GetPermenentRecievers() ?? new MailAddressCollection())
                    {
#if DEBUG               //nur zu mir
                        if (cc.Address.ToLower() != Admin.Address.ToLower())
                        {
                            Console.WriteLine("Send(): Emailadresse CC gesperrt: " + cc.Address);
                        }
                        else
#endif
                        if (!mail.To.Contains(cc))
                        {
                            mail.CC.Add(cc);
                        }
                    }
                }
                #endregion

                #region Message
                if (subject.Length > 0)
                {
                    mail.Subject = subject;
                }
                else
                {
                    mail.Subject = message.Replace(System.Environment.NewLine, "");
                }

                mail.Body = message;
                #endregion

                #region Smtp
                //Siehe https://docs.microsoft.com/de-de/dotnet/api/system.net.mail.smtpclient.sendasync?view=net-5.0

                using var smtpClient = new SmtpClient();

                smtpClient.Host = SmtpHost;
                smtpClient.Port = SmtpPort;

                if (SmtpUser.Length > 0 && SmtpPassword.Length > 0)
                {
                    smtpClient.Credentials = new System.Net.NetworkCredential(SmtpUser, SmtpPassword);
                }

                //smtpClient.UseDefaultCredentials = true;

                smtpClient.EnableSsl = SmtpEnableSSL;

                smtpClient.Send(mail);

                //smtpClient.SendCompleted += SmtpClient_SendCompleted;
                //smtpClient.SendAsync(mail, emailId); //emailId = Zufallszahl größer 255 (Sms-Ids können zwischen 0 bis 255 liegen)
                #endregion
            }
            catch (SmtpFailedRecipientsException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                    if (status == SmtpStatusCode.MailboxBusy ||
                        status == SmtpStatusCode.MailboxUnavailable)
                    {
                        MelBoxSql.Tab_Log.Insert(MelBoxSql.Tab_Log.Topic.Email, 1, $"Senden der Email [{emailId}] fehlgeschlagen. Neuer Sendeversuch.");
                        MelBoxSql.Tab_Sent.UpdateSendStatus(emailId, MelBoxSql.Tab_Sent.Confirmation.RetrySending);

                        System.Threading.Thread.Sleep(5000);
                        using var smtpClient = new SmtpClient();
                        smtpClient.Send(mail);
                    }
                    else
                    {
                        MelBoxSql.Tab_Log.Insert(MelBoxSql.Tab_Log.Topic.Email, 1, $"Fehler beim Senden der Email [{emailId}] an >{ex.InnerExceptions[i].FailedRecipient}<: {ex.InnerExceptions[i].Message}");
                        MelBoxSql.Tab_Sent.UpdateSendStatus(emailId, MelBoxSql.Tab_Sent.Confirmation.AbortedSending);
                    }
                }
            }
            catch (System.Net.Mail.SmtpException ex_smtp)
            {
                MelBoxSql.Tab_Log.Insert(MelBoxSql.Tab_Log.Topic.Email, 1, "Fehler beim Versenden einer Email: " + ex_smtp.Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            MelBoxSql.Tab_Sent.UpdateSendStatus(emailId, MelBoxSql.Tab_Sent.Confirmation.SentSuccessful);
            mail.Dispose();
        }
示例#19
0
        public bool SendMail(string to, string subject, string messageHtml)
        {
            string host                  = "";
            string password              = "";
            string username              = "";
            bool   enableSSL             = false;
            bool   usedefaultcredentials = false;
            int    port                  = 80;
            string fromEmail             = "";
            var    _settings             = _settingService.GetSettingsByType(SettingTypeEnum.EmailSetting);

            if (_settings.Count > 0)
            {
                foreach (Settings setting in _settings)
                {
                    if (setting.Name.ToLower() == "host")
                    {
                        host = setting.Value;
                    }
                    if (setting.Name.ToLower() == "password")
                    {
                        password = setting.Value;
                    }
                    if (setting.Name.ToLower() == "enablessl")
                    {
                        enableSSL = setting.Value.ToLower() == "true" ? true : false;
                    }
                    if (setting.Name.ToLower() == "usedefaultcredentials")
                    {
                        usedefaultcredentials = setting.Value.ToLower() == "true" ? true : false;
                    }
                    if (setting.Name.ToLower() == "port")
                    {
                        port = Convert.ToInt32(setting.Value);
                    }
                    if (setting.Name.ToLower() == "username")
                    {
                        username = setting.Value;
                    }
                    if (setting.Name.ToLower() == "fromemail")
                    {
                        fromEmail = setting.Value;
                    }
                }

                using (MailMessage mail = new MailMessage())
                {
                    if (subject.ToLower() != "Feedback")
                    {
                        mail.From = new MailAddress(fromEmail);
                    }

                    mail.To.Add(to);
                    mail.Subject    = subject;
                    mail.Body       = messageHtml;
                    mail.IsBodyHtml = true;
                    using (SmtpClient smtp = new SmtpClient())
                    {
                        smtp.EnableSsl             = enableSSL;
                        smtp.Host                  = host;
                        smtp.Port                  = port;
                        smtp.UseDefaultCredentials = usedefaultcredentials;
                        smtp.Credentials           = new NetworkCredential(username, password);
                        try
                        {
                            smtp.Send(mail);
                            mail.Dispose();
                        }
                        catch (SmtpFailedRecipientException ex)
                        {
                            SmtpStatusCode statusCode = ex.StatusCode;
                            if (statusCode == SmtpStatusCode.MailboxBusy ||
                                statusCode == SmtpStatusCode.MailboxUnavailable ||
                                statusCode == SmtpStatusCode.TransactionFailed)
                            {
                                Thread.Sleep(5000);
                                smtp.Send(mail);
                                return(true);
                            }
                            else
                            {
                                // System Log
                                var systemLogger = ContextHelper.Current.Resolve <ISystemLogService>();
                                systemLogger.InsertSystemLog(LogLevel.Error, ex.Message, ex.StackTrace);
                            }
                        }
                        finally
                        {
                            mail.Dispose();
                        }
                    }
                }
            }

            return(false);
        }
示例#20
0
        private void SendEmail(DataTable toTable, string From, string Subject, string Body, MailPriority priority)
        {
            //Set up SMTP client to send mail on the lecom mail server
            SmtpClient client = new SmtpClient("mailserver.lecom.edu", 25);

            //Set Email Addresses
            MailAddress MailFrom = new MailAddress(From, NTEnvironment.CurrentUserPrincipal().EmailAddress);
            //TODO: Check if it sends to this email address too

            //Add each address to an array of MailMessages
            List <MailAddress> addressList = new List <MailAddress>();

            for (int r = 0; r < toTable.Rows.Count; r++)
            {
                //Create a mail address with the email address and name
                MailAddress MailToTmp = new MailAddress(toTable.Rows[r][0].ToString().Trim(), toTable.Rows[r][1].ToString().Trim());
                addressList.Add(MailToTmp);
            }

            try
            {
                foreach (MailAddress address in addressList)
                {
                    MailMessage mail = new MailMessage(MailFrom, address);

                    mail.Subject  = Subject;
                    mail.Priority = priority;
                    mail.ReplyToList.Add(mail.From);
                    mail.IsBodyHtml = false;
                    mail.Body       = "Hello " + address.DisplayName.ToString() + ", " + Environment.NewLine + Environment.NewLine + Body;

                    client.Send(mail);
                }

                statusLabel.Text = "Emails sent!";
            }
            catch (SmtpFailedRecipientException ex)
            {
                SmtpStatusCode statusCode = ex.StatusCode;

                if (statusCode == SmtpStatusCode.MailboxBusy ||
                    statusCode == SmtpStatusCode.MailboxUnavailable ||
                    statusCode == SmtpStatusCode.TransactionFailed)
                {
                    statusLabel.Text = "Failed to send to: " + ex.FailedRecipient.ToString();

                    switch (statusCode)
                    {
                    case SmtpStatusCode.MailboxBusy:
                        statusLabel.Text += " (Mailbox Busy)";
                        break;

                    case SmtpStatusCode.MailboxUnavailable:
                        statusLabel.Text += " (Mailbox Unavailable)";
                        break;

                    case SmtpStatusCode.TransactionFailed:
                        statusLabel.Text += " (Transaction Failed)";
                        break;
                    }
                }
                else
                {
                    throw;
                }
            }
        }
示例#21
0
        private int ProcessRead(byte[] buffer, int offset, int read, bool readLine)
        {
            // if 0 bytes were read,there was a failure
            if (read == 0)
            {
                throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
            }

            unsafe
            {
                fixed (byte* pBuffer = buffer)
                {
                    byte* start = pBuffer + offset;
                    byte* ptr = start;
                    byte* end = ptr + read;

                    switch (_readState)
                    {
                        case ReadState.Status0:
                            {
                                if (ptr < end)
                                {
                                    byte b = *ptr++;
                                    if (b < '0' && b > '9')
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }

                                    _statusCode = (SmtpStatusCode)(100 * (b - '0'));

                                    goto case ReadState.Status1;
                                }
                                _readState = ReadState.Status0;
                                break;
                            }
                        case ReadState.Status1:
                            {
                                if (ptr < end)
                                {
                                    byte b = *ptr++;
                                    if (b < '0' && b > '9')
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }

                                    _statusCode += 10 * (b - '0');

                                    goto case ReadState.Status2;
                                }
                                _readState = ReadState.Status1;
                                break;
                            }
                        case ReadState.Status2:
                            {
                                if (ptr < end)
                                {
                                    byte b = *ptr++;
                                    if (b < '0' && b > '9')
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }

                                    _statusCode += b - '0';

                                    goto case ReadState.ContinueFlag;
                                }
                                _readState = ReadState.Status2;
                                break;
                            }
                        case ReadState.ContinueFlag:
                            {
                                if (ptr < end)
                                {
                                    byte b = *ptr++;
                                    if (b == ' ')       // last line
                                    {
                                        goto case ReadState.LastCR;
                                    }
                                    else if (b == '-')  // more lines coming
                                    {
                                        goto case ReadState.ContinueCR;
                                    }
                                    else                // error
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }
                                }
                                _readState = ReadState.ContinueFlag;
                                break;
                            }
                        case ReadState.ContinueCR:
                            {
                                while (ptr < end)
                                {
                                    if (*ptr++ == '\r')
                                    {
                                        goto case ReadState.ContinueLF;
                                    }
                                }
                                _readState = ReadState.ContinueCR;
                                break;
                            }
                        case ReadState.ContinueLF:
                            {
                                if (ptr < end)
                                {
                                    if (*ptr++ != '\n')
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }
                                    if (readLine)
                                    {
                                        _readState = ReadState.Status0;
                                        return (int)(ptr - start);
                                    }
                                    goto case ReadState.Status0;
                                }
                                _readState = ReadState.ContinueLF;
                                break;
                            }
                        case ReadState.LastCR:
                            {
                                while (ptr < end)
                                {
                                    if (*ptr++ == '\r')
                                    {
                                        goto case ReadState.LastLF;
                                    }
                                }
                                _readState = ReadState.LastCR;
                                break;
                            }
                        case ReadState.LastLF:
                            {
                                if (ptr < end)
                                {
                                    if (*ptr++ != '\n')
                                    {
                                        throw new FormatException(SR.SmtpInvalidResponse);
                                    }
                                    goto case ReadState.Done;
                                }
                                _readState = ReadState.LastLF;
                                break;
                            }
                        case ReadState.Done:
                            {
                                int actual = (int)(ptr - start);
                                _readState = ReadState.Done;
                                return actual;
                            }
                    }
                    return (int)(ptr - start);
                }
            }
        }
示例#22
0
 public SmtpException(SmtpStatusCode statusCode, string message) : base(message)
 {
     _statusCode = statusCode;
 }
示例#23
0
        public static MailState Send(MailInfo mailInfo)
        {
            MailConfig mailConfig = SiteConfig.MailConfig;
            MailState  mailcode   = ValidInfo(mailInfo, mailConfig);

            if (mailcode == MailState.None)
            {
                SmtpClient  client      = new SmtpClient();
                MailMessage mailMessage = GetMailMessage(mailInfo, mailConfig);
                try
                {
                    try
                    {
                        client.Host = mailConfig.MailServer;
                        client.Port = mailConfig.Port;
                        NetworkCredential credential         = new NetworkCredential(mailConfig.MailServerUserName, mailConfig.MailServerPassWord);
                        string            authenticationType = string.Empty;
                        switch (mailConfig.AuthenticationType)
                        {
                        case AuthenticationType.None:
                            client.UseDefaultCredentials = false;
                            break;

                        case AuthenticationType.Basic:
                            client.UseDefaultCredentials = true;
                            authenticationType           = "Basic";
                            break;

                        case AuthenticationType.Ntlm:
                            authenticationType = "NTLM";
                            break;
                        }
                        client.EnableSsl      = mailConfig.EnabledSsl;
                        client.Credentials    = credential.GetCredential(mailConfig.MailServer, mailConfig.Port, authenticationType);
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.Send(mailMessage);
                        mailcode = MailState.Ok;
                    }
                    catch (SmtpException exception)
                    {
                        SmtpStatusCode statusCode = exception.StatusCode;
                        if (statusCode != SmtpStatusCode.GeneralFailure)
                        {
                            if (statusCode == SmtpStatusCode.MustIssueStartTlsFirst)
                            {
                                goto Label_01D3;
                            }
                            if (statusCode == SmtpStatusCode.MailboxNameNotAllowed)
                            {
                                goto Label_01CE;
                            }
                            goto Label_01D8;
                        }
                        if (exception.InnerException is IOException)
                        {
                            mailcode = MailState.AttachmentSizeLimit;
                        }
                        else if (exception.InnerException is WebException)
                        {
                            if (exception.InnerException.InnerException == null)
                            {
                                mailcode = MailState.SmtpServerNotFind;
                            }
                            else if (exception.InnerException.InnerException is SocketException)
                            {
                                mailcode = MailState.PortError;
                            }
                        }
                        else
                        {
                            mailcode = MailState.NonsupportSsl;
                        }
                        goto Label_01FA;
Label_01CE:
                        mailcode = MailState.UserNameOrPasswordError;
                        goto Label_01FA;
Label_01D3:
                        mailcode = MailState.MustIssueStartTlsFirst;
                        goto Label_01FA;
Label_01D8:
                        mailcode = MailState.SendFailure;
                    }
                }
                finally
                {
                }
            }
Label_01FA:
            mailInfo.Msg = GetMailStateInfo(mailcode);
            return(mailcode);
        }
示例#24
0
 internal SmtpException(SmtpStatusCode statusCode, string serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage))
 {
     _statusCode = statusCode;
 }
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient)
 {
 }
示例#26
0
 private static string GetMessageForStatus(SmtpStatusCode statusCode, string serverResponse)
 {
     return(GetMessageForStatus(statusCode) + " " + SR.Format(SR.MailServerResponse, serverResponse));
 }
示例#27
0
 internal LineInfo(SmtpStatusCode statusCode, string line)
 {
     _statusCode = statusCode;
     _line       = line;
 }
示例#28
0
        private static string GetMessageForStatus(SmtpStatusCode statusCode)
        {
            switch (statusCode)
            {
            default:
            case SmtpStatusCode.CommandUnrecognized:
                return(SR.Format(SR.SmtpCommandUnrecognized));

            case SmtpStatusCode.SyntaxError:
                return(SR.Format(SR.SmtpSyntaxError));

            case SmtpStatusCode.CommandNotImplemented:
                return(SR.Format(SR.SmtpCommandNotImplemented));

            case SmtpStatusCode.BadCommandSequence:
                return(SR.Format(SR.SmtpBadCommandSequence));

            case SmtpStatusCode.CommandParameterNotImplemented:
                return(SR.Format(SR.SmtpCommandParameterNotImplemented));

            case SmtpStatusCode.SystemStatus:
                return(SR.Format(SR.SmtpSystemStatus));

            case SmtpStatusCode.HelpMessage:
                return(SR.Format(SR.SmtpHelpMessage));

            case SmtpStatusCode.ServiceReady:
                return(SR.Format(SR.SmtpServiceReady));

            case SmtpStatusCode.ServiceClosingTransmissionChannel:
                return(SR.Format(SR.SmtpServiceClosingTransmissionChannel));

            case SmtpStatusCode.ServiceNotAvailable:
                return(SR.Format(SR.SmtpServiceNotAvailable));

            case SmtpStatusCode.Ok:
                return(SR.Format(SR.SmtpOK));

            case SmtpStatusCode.UserNotLocalWillForward:
                return(SR.Format(SR.SmtpUserNotLocalWillForward));

            case SmtpStatusCode.MailboxBusy:
                return(SR.Format(SR.SmtpMailboxBusy));

            case SmtpStatusCode.MailboxUnavailable:
                return(SR.Format(SR.SmtpMailboxUnavailable));

            case SmtpStatusCode.LocalErrorInProcessing:
                return(SR.Format(SR.SmtpLocalErrorInProcessing));

            case SmtpStatusCode.UserNotLocalTryAlternatePath:
                return(SR.Format(SR.SmtpUserNotLocalTryAlternatePath));

            case SmtpStatusCode.InsufficientStorage:
                return(SR.Format(SR.SmtpInsufficientStorage));

            case SmtpStatusCode.ExceededStorageAllocation:
                return(SR.Format(SR.SmtpExceededStorageAllocation));

            case SmtpStatusCode.MailboxNameNotAllowed:
                return(SR.Format(SR.SmtpMailboxNameNotAllowed));

            case SmtpStatusCode.StartMailInput:
                return(SR.Format(SR.SmtpStartMailInput));

            case SmtpStatusCode.TransactionFailed:
                return(SR.Format(SR.SmtpTransactionFailed));

            case SmtpStatusCode.ClientNotPermitted:
                return(SR.Format(SR.SmtpClientNotPermitted));

            case SmtpStatusCode.MustIssueStartTlsFirst:
                return(SR.Format(SR.SmtpMustIssueStartTlsFirst));
            }
        }
示例#29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="SmtpCommandException"/>.
		/// </remarks>
		/// <param name="code">The error code.</param>
		/// <param name="status">The status code.</param>
		/// <param name="mailbox">The rejected mailbox.</param>
		/// <param name="message">The error message.</param>
		internal SmtpCommandException (SmtpErrorCode code, SmtpStatusCode status, MailboxAddress mailbox, string message) : base (message)
		{
			StatusCode = (int) status;
			Mailbox = mailbox;
			ErrorCode = code;
		}
示例#30
0
 public SmtpException(SmtpStatusCode statusCode) : base(GetMessageForStatus(statusCode))
 {
     _statusCode = statusCode;
 }
示例#31
0
 protected SmtpException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
 {
     _statusCode = (SmtpStatusCode)serializationInfo.GetInt32("Status");
 }
示例#32
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="SmtpCommandException"/>.
		/// </remarks>
		/// <param name="code">The error code.</param>
		/// <param name="status">The status code.</param>>
		/// <param name="message">The error message.</param>
		public SmtpCommandException (SmtpErrorCode code, SmtpStatusCode status, string message) : base (message)
		{
			StatusCode = status;
			ErrorCode = code;
		}
示例#33
0
        private static void CheckResponse(SmtpStatusCode statusCode, string serverResponse)
        {
            switch (statusCode)
            {
                case SmtpStatusCode.StartMailInput:
                    {
                        return;
                    }
                case SmtpStatusCode.LocalErrorInProcessing:
                case SmtpStatusCode.TransactionFailed:
                default:
                    {
                        if ((int)statusCode < 400)
                        {
                            throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, serverResponse);
                        }

                        throw new SmtpException(statusCode, serverResponse, true);
                    }
            }
        }
 internal SmtpException(SmtpStatusCode statusCode, string serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode,serverMessage))
 {
     this.statusCode = statusCode;
 }
示例#35
0
        private static void CheckResponse(SmtpStatusCode statusCode, string response)
        {
            switch (statusCode)
            {
                case SmtpStatusCode.ServiceReady:
                    {
                        return;
                    }

                case SmtpStatusCode.ClientNotPermitted:
                default:
                    {
                        if ((int)statusCode < 400)
                        {
                            throw new SmtpException(SR.net_webstatus_ServerProtocolViolation, response);
                        }

                        throw new SmtpException(statusCode, response, true);
                    }
            }
        }
示例#36
0
        public void SendEmail()
        {
            MailMessage mail = new MailMessage();

            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.BodyEncoding    = System.Text.Encoding.UTF8;

            mail.Priority = MailPriority.High;
            mail.Subject  = _subject;

            MailAddress from = new MailAddress(MailFrom);

            mail.From = from;

            string[] mailTo = MailToAddress.Split(',');
            foreach (string m in mailTo)
            {
                MailAddress addr = new MailAddress(m);
                mail.To.Add(addr);
            }

            string[] cc = _cc.Split(',');
            foreach (string c in cc)
            {
                if (!string.IsNullOrEmpty(c))
                {
                    MailAddress ccAddr = new MailAddress(c);
                    mail.CC.Add(ccAddr);
                }
            }

            mail.IsBodyHtml = true;
            mail.Body       = _mailBody;

            SmtpClient masterSMTP = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);

            try
            {
                masterSMTP.Send(mail);
            }
            catch (SmtpFailedRecipientsException smtpEx)
            {
                for (int i = 0; i < smtpEx.InnerExceptions.Length; i++)
                {
                    SmtpStatusCode status = smtpEx.InnerExceptions[i].StatusCode;
                    // If mail server is busy or server is unavailable, mailer will resend mail in 5 minutes.
                    if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
                    {
                        System.Threading.Thread.Sleep(100000);
                        masterSMTP.Send(mail);
                    }
                }
            }
            catch
            {
                SmtpClient slaveSMTP = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
                try
                {
                    slaveSMTP.Send(mail);
                }
                catch (SmtpFailedRecipientsException smtpEx)
                {
                    for (int i = 0; i < smtpEx.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = smtpEx.InnerExceptions[i].StatusCode;
                        // If mail server is busy or server is unavailable, mailer will resend mail in 5 minutes.
                        if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
                        {
                            System.Threading.Thread.Sleep(100000);
                            slaveSMTP.Send(mail);
                        }
                    }
                }
            }
        }
示例#37
0
 internal LineInfo(SmtpStatusCode statusCode, string line)
 {
     _statusCode = statusCode;
     _line = line;
 }
		public SmtpException (SmtpStatusCode statusCode)
			: this (statusCode, "Syntax error, command unrecognized.")
		{
		}
示例#39
0
        public void Email(string subject, string body, string to, string fromdisplayname, string fromemail)
        {
            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(fromemail, fromdisplayname);

                msg.To.Add(to);
                msg.Subject    = subject;
                msg.Body       = body;
                msg.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();

                int    Timeout = Convert.ToInt32(ConfigurationManager.AppSettings["Timeout"].ToString());
                string Host    = ConfigurationManager.AppSettings["Host"].ToString();

                smtp.Timeout = Timeout;
                smtp.Host    = Host;

                string SendEmail             = ConfigurationManager.AppSettings["SendEmail"].ToString();
                string UserName              = ConfigurationManager.AppSettings["UserName"].ToString();
                string Password              = ConfigurationManager.AppSettings["Password"].ToString();
                bool   UseDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["UseDefaultCredentials"].ToString());
                int    Port      = Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString());
                bool   EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"].ToString());

                System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                smtp.UseDefaultCredentials = UseDefaultCredentials;
                NetworkCred.UserName       = UserName;
                NetworkCred.Password       = Password;
                //smtp.Credentials=new NetworkCredential(UserName, Password);
                smtp.Credentials = NetworkCred;
                smtp.Port        = Port;
                smtp.EnableSsl   = EnableSsl;

                smtp.EnableSsl = true;

                //System.Net.Mail.Attachment attachment;
                //attachment = new System.Net.Mail.Attachment(filepath);
                //msg.Attachments.Add(attachment);

                if (SendEmail == "true")
                {
                    try
                    {
                        smtp.Send(msg);

                        string v = msg.ToString();
                    }
                    catch (SmtpFailedRecipientException ex)
                    {
                        SmtpStatusCode statusCode = ex.StatusCode;

                        if (statusCode == SmtpStatusCode.MailboxBusy || statusCode == SmtpStatusCode.MailboxUnavailable || statusCode == SmtpStatusCode.TransactionFailed)
                        {
                            // wait 5 seconds, try a second time

                            Thread.Sleep(120000);
                            smtp.Send(msg);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    finally
                    {
                        msg.Dispose();
                    }
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// Sends an email using smtp server
        /// </summary>
        private void SendEmail()
        {
            // Don't attempt an email if there is no smtp server
            if ((_strSmtpServer != "") && (_strSmtpServer != null))
            {
                try
                {
                    // Create Mail object
                    MailMessage message = new MailMessage();

                    // Set properties needed for the email
                    MailAddress mail_from = new MailAddress(_strEmailFrom);
                    message.From = mail_from;
                    //message.To.Add(_strEmailTo);
                    if (_strEmailTo.Trim().Length > 0)
                    {
                        message.To.Add(_strEmailTo);
                    }
                    if (_strEmailCc.Trim().Length > 0)
                    {
                        message.CC.Add(_strEmailCc);
                    }
                    if (_strEmailBcc.Trim().Length > 0)
                    {
                        message.Bcc.Add(_strEmailBcc);
                    }
                    message.Subject    = _strEmailSubject;
                    message.Body       = _strEmailMessageBody;
                    message.IsBodyHtml = _IsBodyHtml;

                    // TO-DO: Include additional validation for all parameter fields (RegEx)

                    if (_strEmailAttachments.IndexOf(";") > 0)
                    {
                        // Split multiple attachments into a string array
                        Array a = _strEmailAttachments.Split(';');

                        // Loop through attachments list and add to objMail.Attachments one at a time
                        for (int i = 0; i < a.Length; i++)
                        {
                            message.Attachments.Add(new Attachment(a.GetValue(i).ToString().Trim()));
                        }
                    }
                    else if (_strEmailAttachments.Length > 0) // Single attachment without trailing separator
                    {
                        message.Attachments.Add(new Attachment(_strEmailAttachments.ToString().Trim()));
                    }

                    // Set the mail object's smtpserver property
                    SmtpClient SmtpMail = new SmtpClient(_strSmtpServer);
                    //-->SmtpMail.Credentials = (ICredentialsByHost)CredentialCache.DefaultNetworkCredentials;
                    SmtpMail.Send(message);
                }
                //Catch failed recipient error
                catch (SmtpFailedRecipientsException ex)
                {
                    string smtpfailedrecipients_msg = string.Empty;

                    for (int i = 0; i < ex.InnerExceptions.Length; i++)
                    {
                        SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                        if (status == SmtpStatusCode.MailboxBusy ||
                            status == SmtpStatusCode.MailboxUnavailable)
                        {
                            // do nothing
                        }
                        else
                        {
                            smtpfailedrecipients_msg += String.Format("Failed to deliver message to {0}\n",
                                                                      ex.InnerExceptions[i].FailedRecipient);
                        }
                    }

                    throw new SmtpException(smtpfailedrecipients_msg, ex);
                }
                //Catch other errors
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
 protected SmtpException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base (serializationInfo, streamingContext) 
 {
     statusCode = (SmtpStatusCode)serializationInfo.GetInt32("Status");
 }
示例#42
0
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient) : base(statusCode)
 {
     _failedRecipient = failedRecipient;
 }
 static string GetMessageForStatus(SmtpStatusCode statusCode, string serverResponse)
 {
     return GetMessageForStatus(statusCode)+" "+SR.GetString(SR.MailServerResponse,serverResponse);
 }
示例#44
0
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient, string serverResponse) : base(statusCode, serverResponse, true)
 {
     _failedRecipient = failedRecipient;
 }
 public SmtpException(SmtpStatusCode statusCode) : base(GetMessageForStatus(statusCode))
 {
     this.statusCode = statusCode;
 }
示例#46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpCommandException"/>.
 /// </remarks>
 /// <param name="code">The error code.</param>
 /// <param name="status">The status code.</param>
 /// <param name="mailbox">The rejected mailbox.</param>
 /// <param name="message">The error message.</param>
 /// <param name="innerException">The inner exception.</param>
 public SmtpCommandException(SmtpErrorCode code, SmtpStatusCode status, MailboxAddress mailbox, string message, Exception innerException) : base(message, innerException)
 {
     StatusCode = status;
     Mailbox    = mailbox;
     ErrorCode  = code;
 }
示例#47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpCommandException"/>.
 /// </remarks>
 /// <param name="code">The error code.</param>
 /// <param name="status">The status code.</param>>
 /// <param name="message">The error message.</param>
 public SmtpCommandException(SmtpErrorCode code, SmtpStatusCode status, string message) : base(message)
 {
     StatusCode = status;
     ErrorCode  = code;
 }
示例#48
0
        //</snippet29>

        //<snippet30>
        public static SmtpException GenerateSmtpException(SmtpStatusCode status)
        {
            return(new SmtpException(status));
        }
		public SmtpException (string message, Exception innerException)
			: base (message, innerException)
		{
			statusCode = SmtpStatusCode.GeneralFailure;
		}
示例#50
0
        //</snippet30>

        //<snippet31>
        public static SmtpException GenerateSmtpException(SmtpStatusCode status, string message)
        {
            return(new SmtpException(status, message));
        }
 public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient, string serverResponse)
 {
 }
示例#52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpCommandException"/>.
 /// </remarks>
 /// <param name="code">The error code.</param>
 /// <param name="status">The status code.</param>
 /// <param name="mailbox">The rejected mailbox.</param>
 /// <param name="message">The error message.</param>
 internal SmtpCommandException(SmtpErrorCode code, SmtpStatusCode status, MailboxAddress mailbox, string message) : base(message)
 {
     StatusCode = (int)status;
     Mailbox    = mailbox;
     ErrorCode  = code;
 }
 public SmtpException(SmtpStatusCode statusCode, string message)
 {
 }
示例#54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpCommandException"/>.
 /// </remarks>
 /// <param name="code">The error code.</param>
 /// <param name="status">The status code.</param>>
 /// <param name="message">The error message.</param>
 internal SmtpCommandException(SmtpErrorCode code, SmtpStatusCode status, string message) : base(message)
 {
     StatusCode = (int)status;
     ErrorCode  = code;
 }
示例#55
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpResponse"/> class.
		/// </summary>
		/// <param name="code">The status code.</param>
		/// <param name="response">The response text.</param>
		public SmtpResponse (SmtpStatusCode code, string response)
		{
			StatusCode = code;
			Response = response;
		}
示例#56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpResponse"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpResponse"/>.
 /// </remarks>
 /// <param name="code">The status code.</param>
 /// <param name="response">The response text.</param>
 public SmtpResponse(SmtpStatusCode code, string response)
 {
     StatusCode = code;
     Response   = response;
 }
		public SmtpFailedRecipientException (SmtpStatusCode statusCode, string failedRecipient, string serverResponse) : base (statusCode, serverResponse)
		{
			this.failedRecipient = failedRecipient;
		}
示例#58
0
        internal static bool EndSend(IAsyncResult result, out string response)
        {
            SmtpStatusCode statusCode = (SmtpStatusCode)CheckCommand.EndSend(result, out response);

            return(CheckResponse(statusCode, response));
        }
示例#59
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpCommandException"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="SmtpCommandException"/>.
		/// </remarks>
		/// <param name="code">The error code.</param>
		/// <param name="status">The status code.</param>>
		/// <param name="message">The error message.</param>
		internal SmtpCommandException (SmtpErrorCode code, SmtpStatusCode status, string message) : base (message)
		{
			StatusCode = (int) status;
			ErrorCode = code;
		}
示例#60
0
 public void Execute(IJobExecutionContext context)
 {
     try
     {
         string        constrj1         = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
         SqlConnection mainConnectionj1 = new SqlConnection(constrj1);
         mainConnectionj1.Open();
         string        EmailAddress = string.Empty;
         string        Password     = string.Empty;
         string        SmtpServer   = string.Empty;
         int           Port         = 0;
         SqlConnection conj2        = new SqlConnection(constrj1);
         conj2.Open();
         SqlCommand cmdj2 = new SqlCommand("select * from dbo.AbpSettings", conj2);
         DataTable  dtj2  = new DataTable();
         using (SqlDataAdapter sdaj1 = new SqlDataAdapter(cmdj2))
         {
             sdaj1.Fill(dtj2);
         }
         foreach (DataRow datarow2 in dtj2.Rows)
         {
             if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Port")
             {
                 Port = Convert.ToInt32(datarow2["Value"]);
             }
             else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.UserName")
             {
                 EmailAddress = datarow2["Value"].ToString();
             }
             else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Password")
             {
                 Password = datarow2["Value"].ToString();
             }
             else if (datarow2["Name"].ToString() == "Abp.Net.Mail.Smtp.Host")
             {
                 SmtpServer = datarow2["Value"].ToString();
             }
         }
         bool      flag    = false;
         string    queryj1 = string.Concat("select * from dbo.EmailDetail where IsSent='", flag.ToString(), "' and EmailStatus is null");
         DataTable dtj1    = new DataTable();
         using (SqlConnection conj1 = new SqlConnection(constrj1))
         {
             using (SqlCommand cmdj1 = new SqlCommand(queryj1))
             {
                 cmdj1.Connection = conj1;
                 using (SqlDataAdapter sda = new SqlDataAdapter(cmdj1))
                 {
                     sda.Fill(dtj1);
                 }
             }
         }
         foreach (DataRow datarow1 in dtj1.Rows)
         {
             string From     = string.Empty;
             string To       = string.Empty;
             string Cc       = string.Empty;
             string Subject  = string.Empty;
             string MailBody = string.Empty;
             if (datarow1["ToEmailAddress"].ToString() != null)
             {
                 To = datarow1["ToEmailAddress"].ToString();
             }
             if (datarow1["CcEmailAddress"].ToString() != null)
             {
                 Cc = datarow1["CcEmailAddress"].ToString();
             }
             if (datarow1["Subject"].ToString() != null)
             {
                 Subject = datarow1["Subject"].ToString();
             }
             if (datarow1["MailBody"].ToString() != null)
             {
                 MailBody = datarow1["MailBody"].ToString();
             }
             if (Port == 0)
             {
                 Port = 25;
             }
             try
             {
                 this.WriteToFile("Error 1");
                 using (MailMessage mm = new MailMessage(EmailAddress, To))
                 {
                     mm.Subject = Subject;
                     string body = string.Empty;
                     Directory.GetCurrentDirectory();
                     using (StreamReader reader = new StreamReader("C:\\LockedMail\\TibsNotifyMailTemplate.html"))
                     {
                         body = reader.ReadToEnd();
                     }
                     body = body.Replace("{Mail_Body}", MailBody);
                     if (!string.IsNullOrEmpty(Cc))
                     {
                         mm.CC.Add(Cc);
                     }
                     mm.Body       = body;
                     mm.IsBodyHtml = true;
                     SmtpClient smtp = new SmtpClient()
                     {
                         Host      = SmtpServer,
                         EnableSsl = true
                     };
                     NetworkCredential credentials = new NetworkCredential()
                     {
                         UserName = EmailAddress,
                         Password = Password
                     };
                     smtp.UseDefaultCredentials = true;
                     smtp.Credentials           = credentials;
                     smtp.Port = Port;
                     mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                     smtp.DeliveryMethod            = SmtpDeliveryMethod.Network;
                     try
                     {
                         this.WriteToFile("Error 2");
                         smtp.Send(mm);
                     }
                     catch (SmtpFailedRecipientsException smtpFailedRecipientsException)
                     {
                         SmtpFailedRecipientsException ex = smtpFailedRecipientsException;
                         this.WriteToFile("Catch 1");
                         for (int i = 0; i < (int)ex.InnerExceptions.Length; i++)
                         {
                             SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
                             if ((status == SmtpStatusCode.MailboxBusy ? false : status != SmtpStatusCode.MailboxUnavailable))
                             {
                                 this.WriteToFile(string.Concat("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient));
                                 SqlConnection conFinal4 = new SqlConnection(constrj1);
                                 conFinal4.Open();
                                 string qurfinal4 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.InnerExceptions[i].FailedRecipient, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " });
                                 (new SqlCommand(qurfinal4, conFinal4)).ExecuteNonQuery();
                                 conFinal4.Close();
                             }
                             else
                             {
                                 this.WriteToFile(string.Concat("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient));
                                 SqlConnection conFinal4 = new SqlConnection(constrj1);
                                 conFinal4.Open();
                                 string qurfinal4 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.InnerExceptions[i].FailedRecipient, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " });
                                 (new SqlCommand(qurfinal4, conFinal4)).ExecuteNonQuery();
                                 conFinal4.Close();
                             }
                         }
                     }
                     catch (Exception exception)
                     {
                         Exception ex = exception;
                         this.WriteToFile(string.Concat("Exception caught in RetryIfBusy(): {0}", ex.ToString()));
                         SqlConnection conFinal3 = new SqlConnection(constrj1);
                         conFinal3.Open();
                         string qurfinal3 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='", ex.Message, "',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " });
                         (new SqlCommand(qurfinal3, conFinal3)).ExecuteNonQuery();
                         conFinal3.Close();
                     }
                     this.WriteToFile(string.Concat("Email sent successfully to: ", From, " ", To));
                     SqlConnection conFinal = new SqlConnection(constrj1);
                     conFinal.Open();
                     string qurfinal = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='Sent',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " });
                     (new SqlCommand(qurfinal, conFinal)).ExecuteNonQuery();
                     conFinal.Close();
                 }
             }
             catch (Exception exception1)
             {
                 Exception ex = exception1;
                 this.WriteToFile("Catch 2");
                 this.WriteToFile(string.Concat("Error: ", ex.Message));
                 SqlConnection conFinal2 = new SqlConnection(constrj1);
                 conFinal2.Open();
                 string qurfinal2 = string.Concat(new object[] { "update dbo.EmailDetail set IsSent='", true.ToString(), "',EmailStatus='Failed',LastModificationTime='", DateTime.Now, "' where Id='", Convert.ToInt32(datarow1["Id"]), "' " });
                 (new SqlCommand(qurfinal2, conFinal2)).ExecuteNonQuery();
                 conFinal2.Close();
             }
         }
         mainConnectionj1.Close();
     }
     catch (Exception exception2)
     {
         Exception ex = exception2;
         this.WriteToFile(string.Concat("Tibs Notify Service Job1 Error on: ", ex.Message, ex.StackTrace));
     }
 }