public void StartWork()
        {
            if (emailEntry.State == WorkState.Success)
            {
                OnWorkCompleted(WorkState.Success);
                return;
            }

            if (!emailEntry.IsValid)
            {
                OnWorkCompleted(emailEntry.State);
                return;
            }

            emailEntry.State = WorkState.InProgress;

            var message = new EmailMessage(emailEntry.RecipientAddress, emailEntry.EmailSubject, emailEntry.EmailContent, settingsRepository.GetSettings().SenderEmailAddress);
            messageId = message.MessageId;

            apiExtension.SendMessageAsync(message, result =>
                {
                    switch (result.RoutingState)
                    {
                        case RoutingState.DestinationAccepted:
                            if (emailEntry.State == WorkState.InProgress)
                                emailEntry.State = WorkState.Routed;
                            break;
                        case RoutingState.DestinationNotFound:
                            OnWorkCompleted(WorkState.DeliveringFailed);
                            apiExtension.MessageSubmitted -= apiExtension_MessageSubmitted;
                            break;
                    }
                });
        }
Пример #2
0
        private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            var unhandledException = e.Exception;

            var dialog = new MessageDialog($@"Homebased crashed :(
                {Environment.NewLine}Please close the application and try again.
                {Environment.NewLine}But before you do, do you want to mail us the crash report, to see if there's anything we can do?", "Homebased crashed #!$*");
            dialog.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async cmd => 
            {
                var sendTo = new EmailRecipient()
                {
                    Name = "Homebased",
                    Address = "*****@*****.**"
                };

                var mail = new EmailMessage();
                mail.Subject = $"Homebased crashed :(";
                mail.Body = unhandledException.ToString();

                mail.To.Add(sendTo);

                await EmailManager.ShowComposeNewEmailAsync(mail);
            })));

            dialog.Commands.Add(new UICommand("No", new UICommandInvokedHandler(cmd =>
            {
            })));

            await dialog.ShowAsync();
        }
Пример #3
0
        public bool SendEmail(EmailMessage message, bool sendTranslated = false)
        {
            if (message.IsSent)
                return false;

            MailMessage eMessage = new MailMessage();
            eMessage.To.Add(message.To);
            eMessage.From = new MailAddress(message.From);
            eMessage.Subject = message.Subject;

            if (sendTranslated)
                eMessage.Body = message.TranslatedBody;
            else
                eMessage.Body = message.Body;

            eMessage.IsBodyHtml = true;

            try
            {
                _smtpClient.Send(eMessage);
                message.IsSent = true;
                return true;
            }
            catch (Exception ex)
            {
                message.IsSent = false;
                return false;
            }
        }
Пример #4
0
        public void SendEmail(EmailMessage message, string account)
        {
            var fromAddress = new MailAddress(message.From);
            var toAddress = new MailAddress(message.To);

            var mailMessage = new MailMessage(fromAddress, toAddress);            
            mailMessage.Subject = message.Subject;

            if (message.Bcc != null)
            {
                mailMessage.Bcc.Add(new MailAddress(message.Bcc));
            }

            mailMessage.Body = message.Message;
            mailMessage.IsBodyHtml = message.IsHtml;

            var networkCredentials = _credentials.GetCredentialsForAccount(account);
            if (networkCredentials == null)
            {
                throw new Exception(String.Format(
                    "No credentials has been set for account: {0}. Please set up corresponding record in database", account
                    ));
            }

            var client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = networkCredentials;
            client.Host = "mail.trackyt.net";
            client.Port = 587;
            client.EnableSsl = false;
            client.Send(mailMessage);
        }
 private static async Task SendEmail()
 {
     var emailMessage = new EmailMessage();
     emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
     emailMessage.Subject = "Toastmaster Tools Feedback";
     await EmailManager.ShowComposeNewEmailAsync(emailMessage);
 }
Пример #6
0
 private async void ComposeEmail()
 {
     var email = new EmailMessage();
     var recipient = new EmailRecipient("*****@*****.**", "Janerson Douglas");
     email.To.Add(recipient);
     await EmailManager.ShowComposeNewEmailAsync(email);
 }
Пример #7
0
        private async void Developer_Click(object sender, RoutedEventArgs e)
        {
            EmailMessage emailMessage = new EmailMessage();
            emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
            await EmailManager.ShowComposeNewEmailAsync(emailMessage);

        }
Пример #8
0
        public static MailMessage BuildMessageAndViews(EmailMessage message, out AlternateView textView, out AlternateView htmlView)
        {
            var smtpMessage = new MailMessage { BodyEncoding = Encoding.UTF8, From = new MailAddress(message.From) };
            if(message.To.Count > 0) smtpMessage.To.Add(string.Join(",", message.To));
            if(message.ReplyTo.Count > 0) smtpMessage.ReplyToList.Add(string.Join(",", message.ReplyTo));
            if(message.Cc.Count > 0) smtpMessage.CC.Add(string.Join(",", message.Cc));
            if(message.Bcc.Count > 0) smtpMessage.Bcc.Add(string.Join(",", message.Bcc));
            
            htmlView = null;
            textView = null;

            if (!string.IsNullOrWhiteSpace(message.HtmlBody))
            {
                var mimeType = new ContentType("text/html");
                htmlView = AlternateView.CreateAlternateViewFromString(message.HtmlBody, mimeType);
                smtpMessage.AlternateViews.Add(htmlView);
            }

            if (!string.IsNullOrWhiteSpace(message.TextBody))
            {
                const string mediaType = "text/plain";
                textView = AlternateView.CreateAlternateViewFromString(message.TextBody, smtpMessage.BodyEncoding, mediaType);
                textView.TransferEncoding = TransferEncoding.SevenBit;
                smtpMessage.AlternateViews.Add(textView);
            }
            return smtpMessage;
        }
Пример #9
0
 ///<summary>Inserts one EmailMessage into the database.  Returns the new priKey.</summary>
 internal static long Insert(EmailMessage emailMessage)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         emailMessage.EmailMessageNum=DbHelper.GetNextOracleKey("emailmessage","EmailMessageNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(emailMessage,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     emailMessage.EmailMessageNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(emailMessage,false);
     }
 }
Пример #10
0
 ///<summary>Inserts one EmailMessage into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(EmailMessage emailMessage,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         emailMessage.EmailMessageNum=ReplicationServers.GetKey("emailmessage","EmailMessageNum");
     }
     string command="INSERT INTO emailmessage (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="EmailMessageNum,";
     }
     command+="PatNum,ToAddress,FromAddress,Subject,BodyText,MsgDateTime,SentOrReceived) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(emailMessage.EmailMessageNum)+",";
     }
     command+=
              POut.Long  (emailMessage.PatNum)+","
         +"'"+POut.String(emailMessage.ToAddress)+"',"
         +"'"+POut.String(emailMessage.FromAddress)+"',"
         +"'"+POut.String(emailMessage.Subject)+"',"
         +"'"+POut.String(emailMessage.BodyText)+"',"
         +    POut.DateT (emailMessage.MsgDateTime)+","
         +    POut.Int   ((int)emailMessage.SentOrReceived)+")";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         emailMessage.EmailMessageNum=Db.NonQ(command,true);
     }
     return emailMessage.EmailMessageNum;
 }
Пример #11
0
        public static async void OpenEmailClientWithoutPayload()
        {
            IDeviceInfoService _deviceInfoService = ((App)App.Current).Scope.Resolve<IDeviceInfoService>();

            EmailMessage emailMessage = new EmailMessage();

            var credentialsProvider = ((App)Application.Current).Scope.Resolve<ICredentialsProvider>();
            var creds = credentialsProvider.ProvideCredentials(CancellationToken.None);

            var catalogProvider = ((App)Application.Current).Scope.Resolve<ICatalogProvider>();
            var books = await catalogProvider.GetMyBooksFromCache(CancellationToken.None);

            var bookProvider = ((App)Application.Current).Scope.Resolve<IBookProvider>();
            var exists = await bookProvider.GetExistBooks(CancellationToken.None);

            var stringBuilder = new StringBuilder();

            emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
            emailMessage.Body = stringBuilder.ToString();
            try
            {
                await EmailManager.ShowComposeNewEmailAsync(emailMessage);
            }
            catch (Exception e)
            {
                return;
            }
        }
Пример #12
0
        public ActionResult Contact(ContactForm contactForm)
        {
            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Formatting.Indented;
            try
            {
                string subject = "Online Contact From " + contactForm.Name;
                string message = contactForm.Message;
                message += "\r\n\r\n  " + contactForm.Name;
                message += "\r\n   " + contactForm.EmailAddress;
                message += "\r\n   " + contactForm.Number;

                string sendto = Settings.Default.ContactEmail;

                EmailMessage Message = new EmailMessage()
                {
                    Message = message,
                    Subject = subject,
                    EmailAddressFrom = contactForm.EmailAddress,
                    ContactName = contactForm.Name,
                    EmailAddressTo = sendto
                };
                Message.SendMessage();
                Message = null;

                jsonNetResult.Data = new { Result = "success" };
            }
            catch (Exception ex)
            {
                jsonNetResult.Data = new { Result = "fail", Message = ex.Message };
            }
            return jsonNetResult;
        }
Пример #13
0
        /// <summary>
        ///     Creates a MailMessage for the current MailAttribute instance.
        /// </summary>
        protected EmailMessage GenerateProspectiveMailMessage(MailAttributes mail)
        {
            //create base message
            var message = new EmailMessage
            {
                FromName = mail.From.DisplayName,
                FromEmail = mail.From.Address,
                To = mail.To.Union(mail.Cc).Select(t => new EmailAddress(t.Address, t.DisplayName)),
                BccAddress = mail.Bcc.Any() ? mail.Bcc.First().Address : null,
                Subject = mail.Subject,
                Important = mail.Priority == MailPriority.High ? true : false
            };

            // We need to set Reply-To as a custom header
            if (mail.ReplyTo.Any())
            {
                message.AddHeader("Reply-To", string.Join(" , ", mail.ReplyTo));
            }

            // Adding content to the message
            foreach (var view in mail.AlternateViews)
            {
                var reader = new StreamReader(view.ContentStream, Encoding.UTF8, true, 1024, true);

                var body = reader.ReadToEnd();

                if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
                {
                    message.Text = body;
                }
                if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
                {
                    message.Html = body;
                }
            }

            // Going through headers and adding them to the message
            mail.Headers.ToList().ForEach(h => message.AddHeader(h.Key, h.Value));

            // Adding the attachments
            var attachments = new List<EmailAttachment>();
            foreach (var mailAttachment in mail.Attachments.Select(attachment => ActionMailerNext.Utils.AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
            {
                using (var stream = new MemoryStream())
                {
                    mailAttachment.ContentStream.CopyTo(stream);
                    var base64Data = Convert.ToBase64String(stream.ToArray());
                    attachments.Add(new EmailAttachment
                    {
                        Content = base64Data,
                        Name = mailAttachment.Name,
                        Type = mailAttachment.ContentType.MediaType,
                    });
                }
            }

            message.Attachments = attachments;

            return message;
        }
        public void ComposeEmail(IEnumerable<string> to, IEnumerable<string> cc = null, string subject = null, string body = null, bool isHtml = false,
            IEnumerable<EmailAttachment> attachments = null, string dialogTitle = null)
        {
            var message = new EmailMessage
            {
                Subject = subject,
                Body = body
            };

            foreach (var recipient in to)
            {
                message.To.Add(new EmailRecipient(recipient));
            }

            if (cc != null)
            {
                foreach (var recipient in cc)
                {
                    message.CC.Add(new EmailRecipient(recipient));
                }
            }

            if (attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    var stream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromStream(attachment.Content.AsRandomAccessStream());
                    message.Attachments.Add(new Windows.ApplicationModel.Email.EmailAttachment(attachment.FileName, stream));
                }
            }

            EmailManager.ShowComposeNewEmailAsync(message);

        }
Пример #15
0
 private async void hlbFeedback_Click(object sender, RoutedEventArgs e)
 {
     EmailMessage emailMessage = new EmailMessage();
     emailMessage.Subject = "Elementary Notes - Feedback";
     emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
     await EmailManager.ShowComposeNewEmailAsync(emailMessage);
 }
Пример #16
0
        static void Main() {
            Console.WriteLine("Start of publisher");

            Bus.Initialize(cfg => {
                cfg.ReceiveFrom("msmq://localhost/mytestqueue");
                cfg.UseMsmq(mq => mq.UseMulticastSubscriptionClient());
                cfg.VerifyMsDtcConfiguration();
            });
            
            IServiceBus bus = Bus.Instance;
            for (;;) {
                Console.Write("Messsage: ");
                string text = Console.ReadLine();
                if (string.IsNullOrEmpty(text))
                    break;
                char command = text.ToLower()[0];
                string name = text.Substring(1);

                switch (command) {
                    case 'e':
                        var emailMessage = new EmailMessage { Name = name, EmailAddress = "*****@*****.**" };
                        bus.Publish(emailMessage);
                        break;
                    case 'p':
                        var phoneMessage = new PhoneMessage {Name = name, Received = DateTime.Now, PhoneNumber = "(212) 555-1212"};
                        bus.Publish(phoneMessage);
                        break;
                    default:
                        Console.WriteLine("Preceed message with e for email or p for phone call.");
                        break;
                }
            }
        }
Пример #17
0
        protected async void Button1_Click(object sender, EventArgs e)
        {




                MandrillApi api = new MandrillApi("Mandrill Api Key", true);

                IEnumerable<EmailAddress> addresses = new[]
            {
                new EmailAddress("*****@*****.**", "Name Of the Contact"),
                
            };




                var message = new EmailMessage();

                message.FromEmail = "*****@*****.**";
                message.FromName = "Your name";
            message.Html = "emailbody";
                message.Text = "emailbodytext";
            message.Subject = "subject";
                message.To = addresses;
              

                SendMessageRequest req = new SendMessageRequest(message);

                var returnvalue = await api.SendMessage(req);
             
            }
Пример #18
0
 public bool Send(EmailMessage message)
 {
     AlternateView textView;
     AlternateView htmlView;
     var smtpMessage = BuildMessageAndViews(message, out textView, out htmlView);
     try
     {
         _client().Send(smtpMessage);
         return true;
     }
     catch (SmtpException)
     {
         return false;
     }
     finally
     {
         if(htmlView != null)
         {
             htmlView.Dispose();
         }
         if(textView != null)
         {
             textView.Dispose();
         }
     }
 }
        public static void SendThread()
        {
            //create SMTP object
            SMTP objSMTP = new SMTP();
            objSMTP.SMTPServers.Add("smtp.socketlabs.com", 25, 60, SMTPAuthMode.AuthLogin, "your_smtp_user", "your_smtp_password");

            /*
             * this sample just sends one message per thread/connection but in the real world you should send about
             * 50-100 messages per connection. You will have to add your database retrieval and loop management here
             *
             * i.e. grab 50 records from db, connect, loop through and send all 50 and then disconnect
             * repeat as long as there are more records to process in database
            */

            //establish connection and keep it open for all messages we send
            objSMTP.Connect();

            EmailMessage objMessage = new EmailMessage();
            objMessage.From = new Address("*****@*****.**", "Sender Name");
            objMessage.Recipients.Add("*****@*****.**", "Recipient Name", RecipientType.To);
            objMessage.Subject = "Subject...";
            objMessage.BodyParts.Add("Hi ##FIRSTNAME##, Thank you for your interest in ##PRODUCT##.", BodyPartFormat.Plain, BodyPartEncoding.QuotedPrintable);
            Dictionary<string, string> tokens = new Dictionary<string, string>();
            tokens["##FIRSTNAME##"] = "John";
            tokens["##PRODUCT##"] = "SocketLabs Email On-Demand";
            objMessage.BodyParts[0].Body = BulkReplace(objMessage.BodyParts[0].Body, tokens);

            objSMTP.Send(objMessage);

            //close connection after all messages have been sent
            objSMTP.Disconnect();

            Interlocked.Decrement(ref threadsOpen);
        }
Пример #20
0
        public EmailStatus Send(EmailMessage email)
        {
            EmailStatus status = email.Status;
            try
            {
                string emailSender = System.Configuration.ConfigurationManager.AppSettings.Get("email");
                string emailpassword = System.Configuration.ConfigurationManager.AppSettings.Get("emailpassword");
                string notification =System.Configuration.ConfigurationManager.AppSettings.Get("notification");
                string smtp = System.Configuration.ConfigurationManager.AppSettings.Get("smtp");
                int port = int.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("port"));
                bool enableSSL = bool.Parse(System.Configuration.ConfigurationManager.AppSettings.Get("enableSSL"));

                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.From = new MailAddress(emailSender);
                msg.Subject = email.Subject;
                msg.To.Add(email.Recipient.Email);

                //confimacao de leitura
                msg.Headers.Add("Disposition-Notification-To", emailSender);

                msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure |
                                                  DeliveryNotificationOptions.OnSuccess |
                                                  DeliveryNotificationOptions.Delay;

                foreach (var item in email.CC)
                    msg.CC.Add(item.Email);

                foreach (var item in email.CCO)
                    msg.Bcc.Add(item.Email);

                msg.Body = email.ContentMessage;
                msg.IsBodyHtml = email.IsHtmlMessage;

                SmtpClient emailClient = new SmtpClient(smtp);
                System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(emailSender, emailpassword);
                emailClient.UseDefaultCredentials = false;

                emailClient.Credentials = SMTPUserInfo;
                emailClient.Port = port;
                emailClient.EnableSsl = enableSSL;

                foreach (var item in email.Attachments)
                {
                    Attachment attach = new Attachment(new MemoryStream(item.File), item.Name);
                    msg.Attachments.Add(attach);
                }

                emailClient.Send(msg);

                status = EmailStatus.Sent;
            }
            catch (Exception ex)
            {
                email.SetStatusMessage(ex.Message);
                status = EmailStatus.Fail;
            }

            return status;
        }
        public async void Execute(object parameter)
        {
            EmailMessage email = new EmailMessage {Subject = "Contact depuis l'application Windows Phone"};

            email.To.Add(new EmailRecipient("*****@*****.**"));

            await EmailManager.ShowComposeNewEmailAsync(email);
        }
Пример #22
0
        public void Send(EmailMessage message, SmtpParameters sp)
        {
            EmailMessageCollection messages = new EmailMessageCollection();

            messages.Add(message);

            Send(messages, sp);
        }
Пример #23
0
        private async void FeedbackButton_OnClick(object sender, RoutedEventArgs e)
        {
            var em = new EmailMessage();
            em.To.Add(new EmailRecipient("*****@*****.**", "Jason Young"));
            em.Subject = "Keep Moving Feedback";

            await EmailManager.ShowComposeNewEmailAsync(em);
        }
 private async Task SendFeedback()
 {
     var emailMessage = new EmailMessage();
     emailMessage.Body = FeedbackText;
     emailMessage.Subject = "Monocle Giraffe for Windows";
     emailMessage.To.Add(new EmailRecipient("*****@*****.**"));
     await EmailManager.ShowComposeNewEmailAsync(emailMessage);
 }    
 private EmailItem(Object underlyingObject, EmailMessage message, RoutingAddress fromAddress,
                   Stream mimeReadStream)
 {
     _underlyingObject = underlyingObject;
     Message = message;
     FromAddress = fromAddress;
     MimeReadStream = mimeReadStream;
 }
Пример #26
0
 public bool Send(EmailMessage message)
 {
     lock(Messages)
     {
         Messages.Add(message);
         return true;
     }
 }
Пример #27
0
 public async static void Feedback(string subject = "主题", string content = "内容", string to = "RecipientEmail")
 {
     EmailMessage emailMessage = new EmailMessage();
     emailMessage.Subject = subject;
     emailMessage.Body = content;
     emailMessage.To.Add(new EmailRecipient(to));
     await EmailManager.ShowComposeNewEmailAsync(emailMessage); 
 }
Пример #28
0
 private async Task SendFeedbackImpl()
 {
     var message = new EmailMessage();
     message.To.Add(new EmailRecipient(CTime2Resources.Get("Feedback.EmailAddress")));
     message.Subject = CTime2Resources.Get("Feedback.Subject");
     
     await EmailManager.ShowComposeNewEmailAsync(message);
 }
Пример #29
0
            public override void EstablishContext()
            {
                _emailMessage = new EmailMessage(  );
                _emailMessage.AddAttachment( @"c:\file1.txt" );
                _emailMessage.AddAttachment( @"c:\file2.txt" );

                _emailMessage.AddRecipient( @"*****@*****.**" );
                _emailMessage.AddRecipient( @"*****@*****.**" );
            }
Пример #30
0
        /// <summary>
        /// Send a email with attached files.
        /// </summary>
        /// <param name="recipient"></param>
        /// <param name="subject"></param>
        /// <param name="attachment"></param>
        /// <returns></returns>
        public async Task Send(string recipient, string subject, EmailAttachment attachment)
        {
            var email = new EmailMessage();
            email.To.Add(new EmailRecipient(recipient));
            email.Subject = subject;
            email.Attachments.Add(attachment);

            await EmailManager.ShowComposeNewEmailAsync(email);
        }
Пример #31
0
        public ActionResult SendRegistrationEmails(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ClassRoom classRoom = db.ClassRooms.Find(id);
            School    school    = db.Schools.Where(s => s.SchoolID == classRoom.SchoolID).FirstOrDefault();

            if (school == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Data Integrity Error. Classroom not assigned to existing school"));
            }

            try
            {
                List <Student> classStudents = db.Students.Where(s => s.ClassRoomID == id).ToList();
                foreach (Student s in classStudents)
                {
                    EmailMessage email = new EmailMessage();
                    email.EmailSubject    = school.SchoolName + " Online Permission Slip Registration";
                    email.HtmlMessageText = "<a href=\"" + Url.Action("AddStudent", "Manage", new { id = s.ID }, protocol: Request.Url.Scheme) + "\">Click Here to add your student to your profile</a>" +
                                            "<br>" +
                                            "If you haven't registered, you can <a href=\"" + Url.Action("Register", "Account", null, protocol: Request.Url.Scheme) + "\">Click Here to Register</a> first" +
                                            "<p>" +
                                            "Online Permission Slips allows better communication and transparency regarding events for your students' class, " + classRoom.GetClassName() +
                                            "<br />" +
                                            "<br />" +
                                            "<U>You will need to provide the following for verification:</U><br />" +
                                            "<ul>" +
                                            "<li><b>You students ID Number: " + s.StudentNumber.ToString() + "</b></li>" +
                                            "<li><b>Your Student's Full Name: " + s.FullName + "</b></li>" +
                                            "</ul>" +
                                            "</p>" +
                                            "<p>" +
                                            "Online Permission Slips will always protect your student's information, as well as yours, ensuring privacy and limited access to the information." +
                                            "<br>" +
                                            "Only the school and you will be able to access your student's permission slips and related information." +
                                            "</p>";
                    email.MessageText = "Click the following link to add your student to your profile" + Environment.NewLine +
                                        "Click to Add: " + Url.Action("AddStudent", "Manage", new { id = s.ID }, protocol: Request.Url.Scheme) + Environment.NewLine + Environment.NewLine +
                                        "If you haven't registered, you can Click Here to Register first:" + Url.Action("Register", "Account", null, protocol: Request.Url.Scheme) + Environment.NewLine + Environment.NewLine +
                                        "Online Permission Slips allows better communication and transparency regarding events for your students' class, " + classRoom.GetClassName() + Environment.NewLine +
                                        Environment.NewLine +
                                        "You will need to provide the following for verification:" + Environment.NewLine +
                                        "You students ID Number: " + s.StudentNumber.ToString() + Environment.NewLine +
                                        "Your Student's Full Name: " + s.FullName + Environment.NewLine +
                                        Environment.NewLine +
                                        "Online Permission Slips will always protect your student's information, as well as yours, ensuring privacy and limited access to the information." + Environment.NewLine +
                                        "Only the school and you will be able to access your student's permission slips and related information.";

                    if (s.Guardian1TempEmail != null)
                    {
                        email.ToAddress = s.Guardian1TempEmail;
                        MailGunUtility.SendSimpleMessage(email);
                    }
                    if (s.Guardian2TempEmail != null)
                    {
                        email.ToAddress = s.Guardian2TempEmail;
                        MailGunUtility.SendSimpleMessage(email);
                    }
                }
            }
            catch (Exception ex)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Exception Emailing Guardians :: " + ex.ToString()));
            }
            //TODO :: Add Indication that messages were sent??
            return(RedirectToAction("Edit", "ClassRooms", new { id, message = ClassRoomMessageId.EmailsSent }));
        }
Пример #32
0
        private bool TryCreateItem()
        {
            bool bItemCreated = false;

            try
            {
                if (_Folder.FolderClass.StartsWith("IPF.Appointment"))
                {
                    Appointment item = new Appointment(_Service);
                    //item.MimeContent = new MimeContent();

                    //MimeEntry oMimeEntry = new MimeEntry();
                    //oMimeEntry.ShowDialog();
                    string sContent = string.Empty;

                    if (chkIsBase64Encoded.Checked == true)
                    {
                        item.MimeContent.Content = Convert.FromBase64String(txtEntry.Text.Trim());
                    }
                    else
                    {
                        item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(txtEntry.Text);
                    }

                    item.Save(_Folder.Id);

                    bItemCreated = true;
                    item         = null;
                }
                if (_Folder.FolderClass.StartsWith("IPF.Contact"))
                {
                    Contact item = new Contact(_Service);

                    if (chkIsBase64Encoded.Checked == true)
                    {
                        item.MimeContent.Content = Convert.FromBase64String(txtEntry.Text.Trim());
                    }
                    else
                    {
                        item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(txtEntry.Text);
                    }

                    item.Save(_Folder.Id);
                    //this.RefreshContentAndDetails();


                    bItemCreated = true;
                    item         = null;
                }
                if (_Folder.FolderClass.StartsWith("IPF.Note"))
                {
                    EmailMessage item = new EmailMessage(_Service);

                    if (chkIsBase64Encoded.Checked == true)
                    {
                        item.MimeContent.Content = Convert.FromBase64String(txtEntry.Text.Trim());
                    }
                    else
                    {
                        item.MimeContent.Content = System.Text.Encoding.UTF8.GetBytes(txtEntry.Text);
                    }

                    item.Save(_Folder.Id);
                    //this.RefreshContentAndDetails();


                    bItemCreated = true;
                    item         = null;
                }
            }
            catch (Exception ex)
            {
                bItemCreated = false;
                MessageBox.Show(ex.InnerException.ToString(), "Error creating item");
            }

            return(bItemCreated);
        }
Пример #33
0
 public NoteModel(FolderModel folder, [NotNull] EmailMessage obj, ICollection <AttachmentModel> attachments, [NotNull] ExchangeService service)
     : base(folder, obj, attachments, service)
 {
 }
Пример #34
0
 public Task <bool> SendAsync(EmailMessage email)
 {
     return(Task.FromResult(true));
 }
Пример #35
0
 public bool Send(EmailMessage email)
 {
     return(true);
 }
Пример #36
0
        public void Send(GXMailServiceSession sessionInfo, GXMailMessage gxmessage)
        {
            if (_service == null)
            {
                HandleError(2);
                return;
            }
            bool anyError = false;

            string fromAddress = (!string.IsNullOrEmpty(gxmessage.From.Address)) ? gxmessage.From.Address : _userName;

            EmailMessage email = new EmailMessage(_service);

            email.From = new EmailAddress(gxmessage.From.Name, fromAddress);

            SetRecipient(email.ToRecipients, gxmessage.To);
            SetRecipient(email.CcRecipients, gxmessage.CC);
            SetRecipient(email.BccRecipients, gxmessage.BCC);
            SetRecipient(email.ReplyTo, gxmessage.ReplyTo);

            email.Subject = gxmessage.Subject;
            if (string.IsNullOrEmpty(gxmessage.HTMLText))
            {
                email.Body = new MessageBody(BodyType.Text, gxmessage.Text);
            }
            else
            {
                email.Body = new MessageBody(BodyType.HTML, gxmessage.HTMLText);
            }

            foreach (var attach in gxmessage.Attachments)
            {
                string attachFilePath = attach.Trim();
                if (Path.IsPathRooted(attachFilePath))
                {
                    attachFilePath = Path.Combine(_attachDir, attach);
                }
                try
                {
                    email.Attachments.AddFileAttachment(attachFilePath);
                }
                catch (FileNotFoundException)
                {
                    anyError = true;
                    sessionInfo.HandleMailException(new GXMailException("Can't find " + attachFilePath, GXInternetConstants.MAIL_InvalidAttachment));
                }
                catch (Exception e)
                {
                    anyError = true;
                    sessionInfo.HandleMailException(new GXMailException(e.Message, GXInternetConstants.MAIL_InvalidAttachment));
                }
            }

            if (!anyError)
            {
                try
                {
                    email.SendAndSaveCopy(WellKnownFolderName.SentItems);
				}
                catch (Exception e)
                {
                    sessionInfo.HandleMailException(new GXMailException(e.Message, MailConstants.MAIL_MessageNotSent));
                }
            }
        }
 public new void Send(EmailMessage message)
 {
     service.Send(message);
 }
Пример #38
0
        static void Main(string[] args)
        // Validate the server certificate.
        // For a certificate validation code example, see the Validating X509 Certificates topic in the Core Tasks section.
        {
            try
            {
                // Connect to Exchange Web Services as user1 at contoso.com.
                //    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                // Create the binding
                ExchangeService service = new ExchangeService();
                if (service is null)
                {
                    System.Console.WriteLine("service variable is null.");
                }
                else
                {
                    System.Console.WriteLine("service variable created successfully!");
                }
                // Set the credentials for the on-pre server
                // service.Credentials = new WebCredentials("htb\\s.svensson", "Summer2020");
                service.Credentials = new WebCredentials("*****@*****.**", "Summer2020");

                // BypassCertificateError();
                // bool development = true;
                // ServicePointManager.ServerCertificateValidationCallback +=
                //     (sender, certificate, chain, errors) => {
                //         // local dev, just approve all certs
                //         if (development) return true;
                //         return errors == SslPolicyErrors.None ;
                //     };

                ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
                System.Console.WriteLine("1. Passed SSL Certificate Check!");
                // System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                //     (s, cert, chain, sslPolicyErrors) => true;
                // Using Autodiscovery
                // service.AutodiscoverUrl("*****@*****.**");
                // Set the URL manually
                service.Url = new Uri("https://10.10.10.210/EWS/Exchange.asmx");
                System.Console.WriteLine("2. Passed new Uri() Check!");


                // Create the e-mail message, set its properties, and send it to [email protected], saving a copy to the Sent Items folder.
                EmailMessage message = new EmailMessage(service);
                System.Console.WriteLine("3. Passed new EmailMessage()");
                message.Subject = "Interesting";
                message.Body    = "The proposition has been considered.";
                message.ToRecipients.Add("*****@*****.**");
                System.Console.WriteLine("4. Passed message preparation");
                if (message is null)
                {
                    System.Console.WriteLine("message variable is null!");
                }
                else
                {
                    System.Console.WriteLine("Check message Subject: " + message.Subject);
                    System.Console.WriteLine("Before calling SendAndSaveCopy()");

                    // message.Send();
                    // System.Console.WriteLine(message.GetType());

                    message.Save();

                    // message.SendAndSaveCopy();
                    Console.WriteLine("An email with the subject '" + message.Subject + "' has been sent to '" + message.ToRecipients[0] + "' and saved in the SendItems folder.");
                }

                //    System.Console.WriteLine("4.1 message variable: " + message);
                System.Console.WriteLine("5. Passed SendAndSaveCopy()");

                // Write confirmation message to console window.
                Console.WriteLine("Message sent!");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                Console.ReadLine();
            }
        }
Пример #39
0
        protected void ProcessMailItems()
        {
            //Get mailbox items
            ItemView itemView = new ItemView(10);

            itemView.PropertySet = PropertySet.IdOnly;

            FindItemsResults <Item> mailItems       = _service.FindItems(WellKnownFolderName.Inbox, itemView);
            PropertySet             emailProperties = new PropertySet(
                EmailMessageSchema.Sender,
                EmailMessageSchema.DateTimeReceived,
                EmailMessageSchema.Body,
                EmailMessageSchema.Subject);

            emailProperties.RequestedBodyType = BodyType.Text;
            if (mailItems.TotalCount > 0)
            {
                _service.LoadPropertiesForItems(mailItems.Items, emailProperties);
            }

            List <ItemId> emailItemIDs = new List <ItemId>();

            //process each mailbox item
            foreach (Item mailItem in mailItems)
            {
                if (mailItem is EmailMessage)
                {
                    //find or create customer in sharepoint database
                    EmailMessage email    = (EmailMessage)mailItem;
                    Customer     customer = _context.GetCustomerByEmail(email.Sender.Address);
                    if (customer == null)
                    {
                        Customer newCustomer = new Customer()
                        {
                            name   = email.Sender.Name,
                            email  = email.Sender.Address,
                            status = "Prospect"
                        };

                        customer = _context.CreateNewCustomer(newCustomer);
                    }

                    //create contact record from email
                    Contact newContact = new Contact()
                    {
                        customerID   = customer.customerID,
                        contactDate  = email.DateTimeReceived.ToShortDateString(),
                        contactType  = "Email",
                        contactNotes = "Subject: " + email.Subject + "\n\n" + email.Body.Text
                    };

                    Contact savedContact = _context.CreatContact(newContact);

                    //assign agent
                    SalesAgent assignedAgent = (from A in _agents
                                                where A.onlineStatus == "Available"
                                                orderby A.lastMessage descending
                                                select A).FirstOrDefault();

                    if (assignedAgent != null)
                    {
                        //start lync conversation with contactid
                        BeginConversation(assignedAgent, savedContact);

                        //update lead count
                        _leadCount++;

                        //display updated lead count
                        Dispatcher.BeginInvoke(new Action(UpdateLeadCount));
                    }

                    //add item to list of items to get moved to Archive folder
                    emailItemIDs.Add(email.Id);
                }
            }

            if (emailItemIDs.Count > 0)
            {
                //move emails to archive folder
                //create search filter to find specific folder
                SearchFilter filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Archive");

                //use Exchange Web Service to search for folder
                Folder folder = _service.FindFolders(WellKnownFolderName.Inbox, filter, new FolderView(1)).Folders[0];

                //move email items to found folder
                _service.MoveItems(emailItemIDs, folder.Id);
            }
        }
Пример #40
0
        protected void Application_Error(object sender, EventArgs e)
        {
            MandrillApi         mandril  = new MandrillApi(NimbusConfig.MandrillToken);
            EmailMessage        mensagem = new EmailMessage();
            List <EmailAddress> address  = new List <EmailAddress>();

            int httpErrorCode = 500;
            var exception     = Server.GetLastError();

            if (exception is System.Web.HttpException)
            {
                httpErrorCode = ((System.Web.HttpException)exception).GetHttpCode();
            }
            else if (exception is System.Web.Http.HttpResponseException)
            {
                httpErrorCode = (int)((System.Web.Http.HttpResponseException)exception).Response.StatusCode;
            }

            if (exception != null && httpErrorCode == 500) //erros que nao sao 500 o iis que resolva
            {
                string exceptionMsg = exception.ToString();
                if (Context != null)
                {
                    if (Context.Request.Path.Contains("/arterySignalR/"))
                    {
                        return;                                                   //ignora signalr do visual studio
                    }
                    exceptionMsg += "\n\n---- Contexto ----\n" +
                                    "URL: " + Context.Request.RawUrl + "\n" +
                                    "Usuário: " + (Context.User.Identity != null && Context.User.Identity.AuthenticationType == "NimbusUser" ?
                                                   (Context.User.Identity as NimbusUser).Email : "não autenticado") + "\n" +
                                    "Method: " + Context.Request.HttpMethod + "\n" +
                                    "User-Agent: " + Context.Request.UserAgent + "\n" +
                                    "User IP: " + Context.Request.UserHostAddress;
                }
                try
                {
                    mensagem.from_email = "*****@*****.**";
                    mensagem.from_name  = "Nimbus Bug X9";
                    mensagem.subject    = exception.Message;
                    mensagem.text       = exceptionMsg;

                    address.Add(new EmailAddress("***REMOVED***"));
                    address.Add(new EmailAddress("***REMOVED***"));
                    mensagem.to = address;

                    var result = mandril.SendMessage(mensagem);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

            if (httpErrorCode == 404)
            {
                Response.Redirect("/nimbus/pageerror404");
            }
            else
            {
                Response.Redirect("/nimbus/pageerror500");
            }
        }
Пример #41
0
 private static void ValidateReplyToEmailAddresses(EmailMessage emailMessage)
 {
     emailMessage.ReplyTo?.Validate();
 }
Пример #42
0
 private static void ValidateRecipients(EmailMessage emailMessage)
 {
     emailMessage.Recipients.Validate();
 }
 public void Send(EmailMessage msg)
 {
     _sender.SendMessage(msg);
 }
Пример #44
0
        ///<summary>Updates one EmailMessage in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
        public static void Update(EmailMessage emailMessage, EmailMessage oldEmailMessage)
        {
            string command = "";

            if (emailMessage.PatNum != oldEmailMessage.PatNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "PatNum = " + POut.Long(emailMessage.PatNum) + "";
            }
            if (emailMessage.ToAddress != oldEmailMessage.ToAddress)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ToAddress = '" + POut.String(emailMessage.ToAddress) + "'";
            }
            if (emailMessage.FromAddress != oldEmailMessage.FromAddress)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "FromAddress = '" + POut.String(emailMessage.FromAddress) + "'";
            }
            if (emailMessage.Subject != oldEmailMessage.Subject)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Subject = '" + POut.String(emailMessage.Subject) + "'";
            }
            if (emailMessage.BodyText != oldEmailMessage.BodyText)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "BodyText = " + DbHelper.ParamChar + "paramBodyText";
            }
            if (emailMessage.MsgDateTime != oldEmailMessage.MsgDateTime)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "MsgDateTime = " + POut.DateT(emailMessage.MsgDateTime) + "";
            }
            if (emailMessage.SentOrReceived != oldEmailMessage.SentOrReceived)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "SentOrReceived = " + POut.Int((int)emailMessage.SentOrReceived) + "";
            }
            if (emailMessage.RecipientAddress != oldEmailMessage.RecipientAddress)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RecipientAddress = '" + POut.String(emailMessage.RecipientAddress) + "'";
            }
            if (emailMessage.RawEmailIn != oldEmailMessage.RawEmailIn)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RawEmailIn = '" + POut.String(emailMessage.RawEmailIn) + "'";
            }
            if (emailMessage.ProvNumWebMail != oldEmailMessage.ProvNumWebMail)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ProvNumWebMail = " + POut.Long(emailMessage.ProvNumWebMail) + "";
            }
            if (emailMessage.PatNumSubj != oldEmailMessage.PatNumSubj)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "PatNumSubj = " + POut.Long(emailMessage.PatNumSubj) + "";
            }
            if (command == "")
            {
                return;
            }
            if (emailMessage.BodyText == null)
            {
                emailMessage.BodyText = "";
            }
            OdSqlParameter paramBodyText = new OdSqlParameter("paramBodyText", OdDbType.Text, emailMessage.BodyText);

            command = "UPDATE emailmessage SET " + command
                      + " WHERE EmailMessageNum = " + POut.Long(emailMessage.EmailMessageNum);
            Db.NonQ(command, paramBodyText);
        }
Пример #45
0
    /// <summary>
    /// OK click handler (Proceed registration).
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if ((this.PageManager.ViewMode == ViewModeEnum.Design) || (this.HideOnCurrentPage) || (!this.IsVisible))
        {
            // Do not process
        }
        else
        {
            String siteName = CMSContext.CurrentSiteName;

            #region "Banned IPs"

            // Ban IP addresses which are blocked for registration
            if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("banip.ipisbannedregistration");
                return;
            }

            #endregion


            #region "Check Email & password"

            // Check whether user with same email does not exist
            UserInfo ui     = UserInfoProvider.GetUserInfo(txtEmail.Text);
            SiteInfo si     = CMSContext.CurrentSite;
            UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si));

            if ((ui != null) || (siteui != null))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text));
                return;
            }

            // Check whether password is same
            if (passStrength.Text != txtConfirmPassword.Text)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch");
                return;
            }

            if ((this.PasswordMinLength > 0) && (passStrength.Text.Length < this.PasswordMinLength))
            {
                lblError.Visible = true;
                lblError.Text    = String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), this.PasswordMinLength.ToString());
                return;
            }

            if (!passStrength.IsValid())
            {
                lblError.Visible = true;
                lblError.Text    = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName);
                return;
            }

            if (!ValidationHelper.IsEmail(txtEmail.Text.ToLower()))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid");
                return;
            }

            #endregion


            #region "Captcha"

            // Check if captcha is required
            if (this.DisplayCaptcha)
            {
                // Verifiy captcha text
                if (!scCaptcha.IsValid())
                {
                    // Display error message if catcha text is not valid
                    lblError.Visible = true;
                    lblError.Text    = GetString("Webparts_Membership_RegistrationForm.captchaError");
                    return;
                }
                else
                {
                    // Generate new captcha
                    scCaptcha.GenerateNew();
                }
            }

            #endregion


            #region "User properties"

            ui = new UserInfo();
            ui.PreferredCultureCode = "";
            ui.Email      = txtEmail.Text.Trim();
            ui.FirstName  = txtFirstName.Text.Trim();
            ui.FullName   = txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim();
            ui.LastName   = txtLastName.Text.Trim();
            ui.MiddleName = "";

            // User name as put by user (no site prefix included)
            String plainUserName = txtEmail.Text.Trim();
            ui.UserName = plainUserName;

            // Ensure site prefixes
            if (UserInfoProvider.UserNameSitePrefixEnabled(siteName))
            {
                ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text.Trim(), si);
            }

            ui.Enabled  = this.EnableUserAfterRegistration;
            ui.IsEditor = false;
            ui.IsGlobalAdministrator = false;
            ui.UserURLReferrer       = CMSContext.CurrentUser.URLReferrer;
            ui.UserCampaign          = CMSContext.Campaign;

            ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            ui.UserSettings.UserRegistrationInfo.Agent     = HttpContext.Current.Request.UserAgent;

            // Check whether confirmation is required
            bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation");
            bool requiresAdminApprove = false;

            if (!requiresConfirmation)
            {
                // If confirmation is not required check whether administration approval is reqiures
                if ((requiresAdminApprove = SettingsKeyProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")))
                {
                    ui.Enabled = false;
                    ui.UserSettings.UserWaitingForApproval = true;
                }
            }
            else
            {
                // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable
                ui.Enabled = false;
            }

            // Set user's starting alias path
            if (!String.IsNullOrEmpty(this.StartingAliasPath))
            {
                ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(this.StartingAliasPath);
            }

            #endregion


            #region "Reserved names"

            // Check for reserved user names like administrator, sysadmin, ...
            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)));
                return;
            }

            if (UserInfoProvider.NameIsReserved(siteName, plainUserName))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName));
                return;
            }

            #endregion


            #region "License limitations"

            // Check limitations for Global administrator
            if (ui.IsGlobalAdministrator)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedGlobal");
                    return;
                }
            }

            // Check limitations for editors
            if (ui.IsEditor)
            {
                if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Editors, VersionActionEnum.Insert, false))
                {
                    lblError.Visible = true;
                    lblError.Text    = GetString("License.MaxItemsReachedEditor");
                    return;
                }
            }

            // Check limitations for site members
            if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("License.MaxItemsReachedSiteMember");
                return;
            }

            #endregion


            // Check whether email is unique if it is required
            string checkSites = (String.IsNullOrEmpty(this.AssignToSites)) ? siteName : this.AssignToSites;
            if (!UserInfoProvider.IsEmailUnique(txtEmail.Text.Trim(), checkSites, 0))
            {
                lblError.Visible = true;
                lblError.Text    = GetString("UserInfo.EmailAlreadyExist");
                return;
            }

            // Set password
            UserInfoProvider.SetPassword(ui, passStrength.Text);

            #region "Welcome Emails (confirmation, waiting for approval)"

            bool              error    = false;
            EventLogProvider  ev       = new EventLogProvider();
            EmailTemplateInfo template = null;

            string emailSubject = null;
            // Send welcome message with username and password, with confirmation link, user must confirm registration
            if (requiresConfirmation)
            {
                template     = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName);
                emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject"));
            }
            // Send welcome message with username and password, with information that user must be approved by administrator
            else if (this.SendWelcomeEmail)
            {
                if (requiresAdminApprove)
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"));
                }
                // Send welcome message with username and password, user can logon directly
                else
                {
                    template     = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName);
                    emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject"));
                }
            }

            if (template != null)
            {
                // Rretrieve contact ID for confirmation e-mail
                int contactId = 0;
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    // Check if loggin registration activity is enabled
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                    }
                }

                // Prepare macro replacements
                string[,] replacements = new string[6, 2];
                replacements[0, 0]     = "confirmaddress";
                replacements[0, 1]     = (this.ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(this.ApprovalPage) : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx");
                replacements[0, 1]    += "?userguid=" + ui.UserGUID + (contactId > 0?"&contactid=" + contactId.ToString():String.Empty);
                replacements[1, 0]     = "username";
                replacements[1, 1]     = plainUserName;
                replacements[2, 0]     = "password";
                replacements[2, 1]     = passStrength.Text;
                replacements[3, 0]     = "Email";
                replacements[3, 1]     = txtEmail.Text;
                replacements[4, 0]     = "FirstName";
                replacements[4, 1]     = txtFirstName.Text;
                replacements[5, 0]     = "LastName";
                replacements[5, 1]     = txtLastName.Text;

                // Set resolver
                ContextResolver resolver = CMSContext.CurrentResolver;
                resolver.SourceParameters     = replacements;
                resolver.EncodeResolvedValues = true;

                // Email message
                EmailMessage email = new EmailMessage();
                email.EmailFormat = EmailFormatEnum.Default;
                email.Recipients  = ui.Email;

                email.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(siteName + ".CMSNoreplyEmailAddress"));
                email.Body = resolver.ResolveMacros(template.TemplateText);

                resolver.EncodeResolvedValues = false;
                email.PlainTextBody           = resolver.ResolveMacros(template.TemplatePlainText);
                email.Subject = resolver.ResolveMacros(emailSubject);

                email.CcRecipients  = template.TemplateCc;
                email.BccRecipients = template.TemplateBcc;

                try
                {
                    MetaFileInfoProvider.ResolveMetaFileImages(email, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                    // Send the e-mail immediately
                    EmailSender.SendEmail(siteName, email, true);
                }
                catch (Exception ex)
                {
                    ev.LogEvent("E", "RegistrationForm - SendEmail", ex);
                    error = true;
                }
            }

            // If there was some error, user must be deleted
            if (error)
            {
                lblError.Visible = true;
                lblError.Text    = GetString("RegistrationForm.UserWasNotCreated");

                // Email was not send, user can't be approved - delete it
                UserInfoProvider.DeleteUser(ui);
                return;
            }

            #endregion


            #region "Administrator notification email"

            // Notify administrator if enabled and e-mail confirmation is not required
            if (!requiresConfirmation && this.NotifyAdministrator && (this.FromAddress != String.Empty) && (this.ToAddress != String.Empty))
            {
                EmailTemplateInfo mEmailTemplate = null;

                if (requiresAdminApprove)
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName);
                }
                else
                {
                    mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName);
                }

                if (mEmailTemplate == null)
                {
                    // Log missing e-mail template
                    ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri());
                }
                else
                {
                    string[,] replacements = new string[4, 2];
                    replacements[0, 0]     = "firstname";
                    replacements[0, 1]     = ui.FirstName;
                    replacements[1, 0]     = "lastname";
                    replacements[1, 1]     = ui.LastName;
                    replacements[2, 0]     = "email";
                    replacements[2, 1]     = ui.Email;
                    replacements[3, 0]     = "username";
                    replacements[3, 1]     = plainUserName;

                    ContextResolver resolver = CMSContext.CurrentResolver;
                    resolver.SourceParameters     = replacements;
                    resolver.EncodeResolvedValues = true;

                    EmailMessage message = new EmailMessage();

                    message.EmailFormat = EmailFormatEnum.Default;
                    message.From        = EmailHelper.GetSender(mEmailTemplate, this.FromAddress);
                    message.Recipients  = this.ToAddress;
                    message.Body        = resolver.ResolveMacros(mEmailTemplate.TemplateText);

                    resolver.EncodeResolvedValues = false;
                    message.PlainTextBody         = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText);
                    message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject")));

                    message.CcRecipients  = mEmailTemplate.TemplateCc;
                    message.BccRecipients = mEmailTemplate.TemplateBcc;

                    try
                    {
                        // Attach template meta-files to e-mail
                        MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE);
                        EmailSender.SendEmail(siteName, message);
                    }
                    catch
                    {
                        ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID);
                    }
                }
            }

            #endregion


            #region "Web analytics"

            // Track successful registration conversion
            if (this.TrackConversionName != String.Empty)
            {
                if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress))
                {
                    // Log conversion
                    HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, this.TrackConversionName, 0, ConversionValue);
                }
            }

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                AnalyticsHelper.LogRegisteredUser(siteName, ui);
            }

            #endregion

            #region "On-line marketing - activity"

            // Log registered user if confirmation is not required
            if (!requiresConfirmation)
            {
                if (ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName))
                {
                    int contactId = 0;
                    // Log registration activity
                    if (ActivitySettingsHelper.UserRegistrationEnabled(siteName))
                    {
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                            ActivityLogProvider.LogRegistrationActivity(contactId,
                                                                        ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture);
                        }
                    }

                    // Log login activity
                    if (ui.Enabled && ActivitySettingsHelper.UserLoginEnabled(siteName))
                    {
                        if (contactId <= 0)
                        {
                            contactId = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui);
                        }
                        ActivityLogHelper.UpdateContactLastLogon(contactId);    // Update last logon time
                        if (ActivitySettingsHelper.ActivitiesEnabledForThisUser(ui))
                        {
                            ActivityLogProvider.LogLoginActivity(contactId,
                                                                 ui, URLHelper.CurrentRelativePath, CMSContext.CurrentDocument.DocumentID, siteName, CMSContext.Campaign, CMSContext.CurrentDocument.DocumentCulture);
                        }
                    }
                }
            }

            #endregion

            #region "Roles & authentication"

            string[] roleList = this.AssignRoles.Split(';');
            string[] siteList;

            // If AssignToSites field set
            if (!String.IsNullOrEmpty(this.AssignToSites))
            {
                siteList = this.AssignToSites.Split(';');
            }
            else // If not set user current site
            {
                siteList = new string[] { siteName };
            }

            foreach (string sn in siteList)
            {
                // Add new user to the current site
                UserInfoProvider.AddUserToSite(ui.UserName, sn);
                foreach (string roleName in roleList)
                {
                    if (!String.IsNullOrEmpty(roleName))
                    {
                        String s = roleName.StartsWith(".") ? "" : siteName;

                        // Add user to desired roles
                        if (RoleInfoProvider.RoleExists(roleName, s))
                        {
                            UserInfoProvider.AddUserToRole(ui.UserName, roleName, s);
                        }
                    }
                }
            }

            if (this.DisplayMessage.Trim() != String.Empty)
            {
                pnlForm.Visible = false;
                lblText.Visible = true;
                lblText.Text    = this.DisplayMessage;
            }
            else
            {
                if (ui.Enabled)
                {
                    CMSContext.AuthenticateUser(ui.UserName, true);
                }

                if (this.RedirectToURL != String.Empty)
                {
                    URLHelper.Redirect(this.RedirectToURL);
                }

                else if (QueryHelper.GetString("ReturnURL", "") != String.Empty)
                {
                    string url = QueryHelper.GetString("ReturnURL", "");

                    // Do url decode
                    url = Server.UrlDecode(url);

                    // Check that url is relative path or hash is ok
                    if (url.StartsWith("~") || url.StartsWith("/") || QueryHelper.ValidateHash("hash"))
                    {
                        URLHelper.Redirect(url);
                    }
                    // Absolute path with wrong hash
                    else
                    {
                        URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext")));
                    }
                }
            }

            #endregion

            lblError.Visible = false;
        }
    }
 public void EnviarCorreoAsync(EmailMessage email)
 {
     EnviarCorreoAsync(email, null);
 }
Пример #47
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);
        }
Пример #48
0
    /// <summary>
    /// Sets new UserInfo for approved user.
    /// </summary>
    /// <param name="userID">User to be approved</param>
    protected void SetUserInfo(int userID)
    {
        UserInfo user = UserInfoProvider.GetFullUserInfo(userID);

        // Cancel waiting for approval attribute
        user.UserSettings.UserWaitingForApproval = false;
        // Set activation time to now
        user.UserSettings.UserActivationDate = DateTime.Now;
        // Set user who activated this account
        user.UserSettings.UserActivatedByUserID = MembershipContext.AuthenticatedUser.UserID;
        // Enable user
        user.Enabled = true;

        UserInfoProvider.SetUserInfo(user);

        // Send e-mail to user
        if (!String.IsNullOrEmpty(user.Email))
        {
            EmailTemplateInfo template = EmailTemplateProvider.GetEmailTemplate("RegistrationUserApproved", SiteContext.CurrentSiteName);
            if (template != null)
            {
                string from = EmailHelper.GetSender(template, SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSNoreplyEmailAddress"));
                if (!String.IsNullOrEmpty(from))
                {
                    EmailMessage email = new EmailMessage();
                    email.EmailFormat = EmailFormatEnum.Default;
                    // Get e-mail sender and subject from template, if used
                    email.From       = from;
                    email.Recipients = user.Email;

                    MacroResolver resolver = MembershipResolvers.GetRegistrationApprovalResolver(user, URLHelper.GetAbsoluteUrl("~/"));

                    // Enable encoding of macro results for HTML mail body
                    resolver.Settings.EncodeResolvedValues = true;
                    email.Body = resolver.ResolveMacros(template.TemplateText);

                    // Disable encoding of macro results for plaintext body and subject
                    resolver.Settings.EncodeResolvedValues = false;
                    string emailSubject = EmailHelper.GetSubject(template, GetString("registrationform.registrationapprovalemailsubject"));
                    email.Subject = resolver.ResolveMacros(emailSubject);

                    email.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText);

                    email.CcRecipients  = template.TemplateCc;
                    email.BccRecipients = template.TemplateBcc;

                    try
                    {
                        // Add attachments
                        EmailHelper.ResolveMetaFileImages(email, template.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE);
                        EmailSender.SendEmail(SiteContext.CurrentSiteName, email);
                    }
                    catch
                    {
                        EventLogProvider.LogEvent(EventType.ERROR, "Membership", "WaitingForApprovalEmail");
                    }
                }
                else
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "WaitingForApproval", "EmailSenderNotSpecified");
                }
            }
            else
            {
                // Log missing e-mail template
                try
                {
                    EventLogProvider.LogEvent(EventType.ERROR, "RegistrationUserApproved", "GetEmailTemplate", eventUrl: RequestContext.RawURL);
                }
                catch
                {
                }
            }
        }

        // User is approved and enabled, could be logged into statistics
        AnalyticsHelper.LogRegisteredUser(SiteContext.CurrentSiteName, user);
    }
Пример #49
0
        //private static void accessEmail(string cred, Options options)
        private static void accessEmail(List <string> credList, Options options)
        {
            foreach (var cred in credList)
            {
                string[] creds    = cred.Split('|');
                string   username = creds[0];
                string   password = creds[1].Trim();
                Console.WriteLine("\nChecking: " + username);
                if (username.Length == 0)
                {
                    Console.WriteLine("The username is empty");
                    System.Environment.Exit(1);
                }
                if (password.Length == 0)
                {
                    Console.WriteLine("The password is empty: " + username);
                }
                if (password.Length > 0 && username.Length > 0)
                {
                    char[]   separatingChars = { '@' };
                    string[] filename        = username.Split('@');
                    bool     passPreReq      = true;


                    //Set fake timezone to fix issue with Mono on OSX
                    string       displayName  = "(GMT+06:00) Antartica/Mawson Time";
                    string       standardName = "Eastern Standard Time";
                    TimeSpan     offset       = new TimeSpan(06, 00, 00);
                    TimeZoneInfo mawson       = TimeZoneInfo.CreateCustomTimeZone(standardName, offset, displayName, standardName);

                    ExchangeService service = new ExchangeService();

                    ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallback;
                    try
                    {
                        service = new ExchangeService(mawson);
                        service.EnableScpLookup = false;
                        service.Credentials     = new WebCredentials(username, password);
                        service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                        SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                        FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                    }
                    catch (Exception e)
                    {
                        if (options.verbose == true)
                        {
                            Console.WriteLine(e);
                        }
                        try
                        {
                            service = new ExchangeService(ExchangeVersion.Exchange2007_SP1, mawson);
                            service.EnableScpLookup = false;
                            service.Credentials     = new WebCredentials(username, password);
                            service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                            SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                            FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                        }
                        catch (Exception e1)
                        {
                            if (options.verbose == true)
                            {
                                Console.WriteLine(e1);
                            }
                            try
                            {
                                if (e1.Message.Contains("Microsoft.Exchange.WebServices.Data.ExchangeVersion"))
                                {
                                    service = new ExchangeService(ExchangeVersion.Exchange2013_SP1, mawson);
                                    service.EnableScpLookup = false;
                                    service.Credentials     = new WebCredentials(username, password);
                                    service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                                    SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                                    FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                                }
                                else
                                {
                                    passPreReq = false;
                                    Console.WriteLine("Incorrect username or password: "******"Microsoft.Exchange.WebServices.Data.ExchangeVersion"))
                                    {
                                        service = new ExchangeService(ExchangeVersion.Exchange2013, mawson);
                                        service.EnableScpLookup = false;
                                        service.Credentials     = new WebCredentials(username, password);
                                        service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                                        SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                                        FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                                    }
                                    else
                                    {
                                        passPreReq = false;
                                        Console.WriteLine("Incorrect username or password: "******"Microsoft.Exchange.WebServices.Data.ExchangeVersion"))
                                        {
                                            service = new ExchangeService(ExchangeVersion.Exchange2010_SP2, mawson);
                                            service.EnableScpLookup = false;
                                            service.Credentials     = new WebCredentials(username, password);
                                            service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                                            SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                                            FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                                        }
                                        else
                                        {
                                            passPreReq = false;
                                            Console.WriteLine("Incorrect username or password: "******"Microsoft.Exchange.WebServices.Data.ExchangeVersion"))
                                            {
                                                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1, mawson);
                                                service.EnableScpLookup = false;
                                                service.Credentials     = new WebCredentials(username, password);
                                                service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                                                SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                                                FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                                            }
                                        }
                                        catch (Exception e5)
                                        {
                                            Console.WriteLine(e5);
                                            if (e5.Message.Contains("Microsoft.Exchange.WebServices.Data.ExchangeVersion"))
                                            {
                                                service = new ExchangeService(ExchangeVersion.Exchange2010, mawson);
                                                service.EnableScpLookup = false;
                                                service.Credentials     = new WebCredentials(username, password);
                                                service.AutodiscoverUrl(username, RedirectionUrlValidationCallback);
                                                SearchFilter       searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Inbox");
                                                FindFoldersResults f            = service.FindFolders(WellKnownFolderName.MsgFolderRoot, searchFilter, new FolderView(1));
                                            }
                                            else
                                            {
                                                passPreReq = false;
                                                Console.WriteLine("Incorrect username or password: "******"password", ContainmentMode.Substring, ComparisonMode.IgnoreCase)));
                                searchFilterCollection.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Body, "creds", ContainmentMode.Substring, ComparisonMode.IgnoreCase)));
                                searchFilterCollection.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Body, "credentials", ContainmentMode.Substring, ComparisonMode.IgnoreCase)));
                                searchFilterCollection.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Body, "ssn", ContainmentMode.Substring, ComparisonMode.IgnoreCase)));
                                searchFilterCollection.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.Or, new SearchFilter.ContainsSubstring(ItemSchema.Body, "credit card", ContainmentMode.Substring, ComparisonMode.IgnoreCase)));
                            }
                            else
                            {
                                //Iterate through each mail in Inbox
                                Folder   inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                                ItemView view  = new ItemView(100);
                                FindItemsResults <Item> findResults2;
                                do
                                {
                                    findResults2 = service.FindItems(WellKnownFolderName.Inbox, view);
                                    foreach (var item in findResults2.Items)
                                    {
                                        PropertySet props2   = new PropertySet(EmailMessageSchema.Body);
                                        var         email2   = EmailMessage.Bind(service, item.Id, props2);
                                        string      sPattern = "\b4[0-9]{12}(?:[0-9]{3})?\b";
                                        //string sPattern = "^5[1-5][0-9]{14}$";
                                        //string sPattern = "[pP]assword";

                                        if (email2.Body.Text.Length > 0)
                                        {
                                            if (Regex.IsMatch(email2.Body.Text, sPattern))
                                            {
                                                Console.WriteLine("\n[PAN] PAN Number found in: " + filename[0] + "_" + "Inbox" + i + ".eml");

                                                string emlFilename = @filename[0] + "_" + "Inbox" + i + ".eml";
                                                ++i;
                                                PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);
                                                var         email = EmailMessage.Bind(service, item.Id, props);

                                                using (FileStream fs = new FileStream(emlFilename, FileMode.Create, FileAccess.Write))
                                                {
                                                    fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
                                                }

                                                ++i;
                                            }
                                        }
                                    }
                                    view.Offset = findResults2.NextPageOffset.Value;
                                } while (findResults2.MoreAvailable);
                            }
                        }
                        if (options.pan == false)
                        {
                            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());

                            //Inbox
                            FindItemsResults <Item> findResults = service.FindItems(
                                WellKnownFolderName.Inbox,
                                searchFilter,
                                new ItemView(999));

                            foreach (var item in findResults)
                            {
                                Console.WriteLine("[Subject]: " + item.Subject);
                                //Console.WriteLine(item.HasAttachments);
                                string emlFilename = @filename[0] + "_" + "Inbox" + i + ".eml";
                                ++i;
                                PropertySet props = new PropertySet(EmailMessageSchema.MimeContent);
                                var         email = EmailMessage.Bind(service, item.Id, props);
                                Console.WriteLine("Writing to file: {0}\n", emlFilename);
                                using (FileStream fs = new FileStream(emlFilename, FileMode.Create, FileAccess.Write))
                                {
                                    fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #50
0
        /// <summary>
        /// SendMail function utilized by llEMail
        /// </summary>
        /// <param name="objectID"></param>
        /// <param name="address"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public void SendEmail(UUID objectID, string address, string subject, string body)
        {
            //Check if address is empty
            if (address == string.Empty)
            {
                return;
            }

            //FIXED:Check the email is correct form in REGEX
            string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                                        + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                                        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                                        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                                        + @"[a-zA-Z]{2,}))$";
            Regex EMailreStrict      = new Regex(EMailpatternStrict);
            bool  isEMailStrictMatch = EMailreStrict.IsMatch(address);

            if (!isEMailStrictMatch)
            {
                m_log.Error("[EMAIL] REGEX Problem in EMail Address: " + address);
                return;
            }
            //FIXME:Check if subject + body = 4096 Byte
            if ((subject.Length + body.Length) > 1024)
            {
                m_log.Error("[EMAIL] subject + body > 1024 Byte");
                return;
            }

            string LastObjectName       = string.Empty;
            string LastObjectPosition   = string.Empty;
            string LastObjectRegionName = string.Empty;

            resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);

            if (!address.EndsWith(m_InterObjectHostname))
            {
                // regular email, send it out
                try
                {
                    //Creation EmailMessage
                    EmailMessage emailMessage = new EmailMessage();
                    //From
                    emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
                    //To - Only One
                    emailMessage.AddToAddress(new EmailAddress(address));
                    //Subject
                    emailMessage.Subject = subject;
                    //TEXT Body
                    resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
                    emailMessage.BodyText = "Object-Name: " + LastObjectName +
                                            "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                            LastObjectPosition + "\n\n" + body;

                    //Config SMTP Server
                    //Set SMTP SERVER config
                    SmtpServer smtpServer = new SmtpServer(SMTP_SERVER_HOSTNAME, SMTP_SERVER_PORT);
                    // Add authentication only when requested
                    //
                    if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
                    {
                        //Authentication
                        smtpServer.SmtpAuthToken = new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
                    }
                    //Send Email Message
                    emailMessage.Send(smtpServer);

                    //Log
                    m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
                }
                catch (Exception e)
                {
                    m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
                }
            }
            else
            {
                // inter object email, keep it in the family
                Email email = new Email();
                email.time    = ((int)((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)).ToString();
                email.subject = subject;
                email.sender  = objectID.ToString() + "@" + m_InterObjectHostname;
                email.message = "Object-Name: " + LastObjectName +
                                "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
                                LastObjectPosition + "\n\n" + body;

                string guid = address.Substring(0, address.IndexOf("@"));
                UUID   toID = new UUID(guid);

                if (IsLocal(toID)) // TODO FIX check to see if it is local
                {
                    // object in this region
                    InsertEmail(toID, email);
                }
                else
                {
                    // object on another region
                    // TODO FIX
                }
            }

            //DONE: Message as Second Life style
            //20 second delay - AntiSpam System - for now only 10 seconds
            DelayInSeconds(10);
        }
Пример #51
0
        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            userName        = settings.UserName;
            password        = settings.Password;
            domain          = settings.Domain;
            serviceURL      = settings.ServiceUrl;
            exchangeVersion = settings.ExchangeVersion;

            emailID      = request.Inputs["Email ID"].AsString();
            SaveLocation = request.Inputs["Save Location"].AsString();

            numberOfExportedEmails = 0;

            string alternateMailbox = string.Empty;

            if (request.Inputs.Contains("Alternate Mailbox"))
            {
                alternateMailbox = request.Inputs["Alternate Mailbox"].AsString();
            }

            ExchangeService service = new ExchangeService();

            switch (exchangeVersion)
            {
            case "Exchange2007_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                break;

            case "Exchange2010":
                service = new ExchangeService(ExchangeVersion.Exchange2010);
                break;

            case "Exchange2010_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                break;

            default:
                service = new ExchangeService();
                break;
            }

            service.Credentials = new WebCredentials(userName, password, domain);
            String AccountUrl = userName + "@" + domain;

            if (serviceURL.Equals("Autodiscover"))
            {
                service.AutodiscoverUrl(AccountUrl, (a) => { return(true); });
            }
            else
            {
                service.Url = new Uri(serviceURL);
            }

            if (!alternateMailbox.Equals(String.Empty))
            {
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox);
            }

            PropertySet  propSet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent, EmailMessageSchema.IsRead);
            EmailMessage message = EmailMessage.Bind(service, emailID, propSet);

            response.PublishRange(exportEmail(message));
            response.Publish("Number of Exported Emails", numberOfExportedEmails);
        }
Пример #52
0
        private void EmailScannedImages()
        {
            if (imageList.Images.Count == 0)
            {
                errorOutput.DisplayError(ConsoleResources.NoPagesToEmail);
                return;
            }


            OutputVerbose(ConsoleResources.Emailing);

            var message = new EmailMessage
            {
                Subject    = fileNamePlaceholders.SubstitutePlaceholders(options.EmailSubject, startTime, false) ?? "",
                BodyText   = fileNamePlaceholders.SubstitutePlaceholders(options.EmailBody, startTime, false),
                AutoSend   = options.EmailAutoSend,
                SilentSend = options.EmailSilentSend
            };

            message.Recipients.AddRange(EmailRecipient.FromText(EmailRecipientType.To, options.EmailTo));
            message.Recipients.AddRange(EmailRecipient.FromText(EmailRecipientType.Cc, options.EmailCc));
            message.Recipients.AddRange(EmailRecipient.FromText(EmailRecipientType.Bcc, options.EmailBcc));

            var tempFolder = new DirectoryInfo(Path.Combine(Paths.Temp, Path.GetRandomFileName()));

            tempFolder.Create();
            try
            {
                string attachmentName = fileNamePlaceholders.SubstitutePlaceholders(options.EmailFileName, startTime, false);
                string targetPath     = Path.Combine(tempFolder.FullName, attachmentName);
                if (IsPdfFile(targetPath))
                {
                    if (options.OutputPath != null && IsPdfFile(options.OutputPath))
                    {
                        // The scan has already been exported to PDF, so use that file
                        OutputVerbose(ConsoleResources.AttachingExportedPDF, attachmentName);
                        message.Attachments.Add(new EmailAttachment
                        {
                            FilePath       = actualOutputPath,
                            AttachmentName = attachmentName
                        });
                    }
                    else
                    {
                        // The scan hasn't bee exported to PDF yet, so it needs to be exported to the temp folder
                        OutputVerbose(ConsoleResources.ExportingPDFToAttach);
                        if (!DoExportToPdf(targetPath, true))
                        {
                            OutputVerbose(ConsoleResources.EmailNotSent);
                            return;
                        }
                        // Attach the PDF file
                        AttachFilesInFolder(tempFolder, message);
                    }
                }
                else
                {
                    // Export the images to the temp folder
                    // Don't bother to re-use previously exported images, because the possible different formats and multiple files makes it non-trivial,
                    // and exporting is pretty cheap anyway
                    OutputVerbose(ConsoleResources.ExportingImagesToAttach);
                    DoExportToImageFiles(targetPath);
                    // Attach the image file(s)
                    AttachFilesInFolder(tempFolder, message);
                }

                OutputVerbose(ConsoleResources.SendingEmail);
                if (emailer.SendEmail(message))
                {
                    OutputVerbose(ConsoleResources.EmailSent);
                }
                else
                {
                    OutputVerbose(ConsoleResources.EmailNotSent);
                }
            }
            finally
            {
                tempFolder.Delete(true);
            }
        }
Пример #53
0
 public MimeMessageBuilderException(EmailMessage emailMessage, Exception innerException)
     : base($"Could not create MimeMessage for EmailMessage.", emailMessage, innerException)
 {
 }
Пример #54
0
        public void CreateRecipientListWithNoRecipients()
        {
            EmailMessage emailMessage = new EmailMessage(IntegrationResultMother.CreateFixed(), new EmailPublisher());

            Assert.AreEqual(string.Empty, emailMessage.Recipients);
        }
Пример #55
0
        static void Main(string[] args)
        {
            ssReports        report = new ssReports();
            InternalEntities db     = new InternalEntities();

            //string dtback = DateTime.Now.ToString("yyyy-MM-dd");
            //DateTime date = Convert.ToDateTime(dtback);

            DateTime dtt = DateTime.Now;

            dtt = dtt.AddHours(-12);

            string dt          = DateTime.Now.ToString("MMddyyyyhhmmss");
            string path        = @"ExportedFiles\";
            string filename    = "OLER" + dt + ".xlsx";
            string log         = @"Logs\";
            string logfilename = dt + ".txt";

            if (!Directory.Exists(log))
            {
                Directory.CreateDirectory(log);
            }

            FileStream filestream   = new FileStream(log + logfilename, FileMode.Create);
            var        streamwriter = new StreamWriter(filestream);

            streamwriter.AutoFlush = true;
            Console.SetOut(streamwriter);
            Console.SetError(streamwriter);

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                report.CreateExcelDoc(path + filename);

                streamwriter.WriteLine("Excel file has been created!");
            }

            catch (Exception ex)
            {
                streamwriter.WriteLine(ex.ToString());
            }

            try
            {
                String[] mEmailTo      = ConfigurationManager.AppSettings["EmailTo"].ToString().Split(',');
                string   mEmailFrom    = ConfigurationManager.AppSettings["EmailFrom"];
                string   mEmailSubject = ConfigurationManager.AppSettings["EmailSubject"];

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.UseDefaultCredentials = true;
                service.AutodiscoverUrl(mEmailFrom, RedirectionUrlValidationCallback);

                EmailMessage email = new EmailMessage(service);
                foreach (String s in mEmailTo)
                {
                    email.ToRecipients.Add(s);
                }

                email.Subject = mEmailSubject;
                email.Body    = new MessageBody("This email contains attachments");
                email.Attachments.AddFileAttachment(path + filename);

                streamwriter.WriteLine("Sending email...");
                email.Send();
                streamwriter.WriteLine("Email Sent....!");

                var entries = db.OnlineExpedites.Where(d => d.CreationDate > dtt || d.DateSentTimeStamp == null);
                if (entries != null)
                {
                    foreach (var entry in entries)
                    {
                        entry.DateSentTimeStamp = DateTime.Now;
                    }
                    db.SaveChanges();
                }

                streamwriter.WriteLine("Database Updated.....");
            }
            catch (Exception ex)
            {
                streamwriter.WriteLine(ex.ToString());
            }
        }
Пример #56
0
        public Boolean CreateNewUser(string firstName, string middleName, string lastName, DateTime dateOfBirth, string phone1, string phone2, string email, string employerName, string officeAddress1, string officeAddress2, string officeState)
        {
            bool flag;

            //use OWA to send out email and log the entry into a database table
            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

            service.Credentials  = new WebCredentials("*****@*****.**", "legacy12.");
            service.TraceEnabled = true;
            service.TraceFlags   = TraceFlags.All;
            service.AutodiscoverUrl("*****@*****.**", RedirectionUrlValidationCallback);

            string       receipient  = "*****@*****.**";
            EmailMessage emailSender = new EmailMessage(service);

            emailSender.ToRecipients.Add(receipient);
            emailSender.Subject = "NEW ACCOUNT GENERATION (LEAD DERIVED FROM FCMB MOBILE APPLICATION)";
            emailSender.Body    = "<html xmlns=" + "http://www.w3.org/1999/xhtml" + ">" +
                                  "<head runat=" + "server" + ">" +
                                  "<title></title>" +
                                  "<style type=" + "text/css" + ">" +
                                  ".style1" +
                                  "{" +
                                  "width: 175px;" +
                                  "}" +
                                  ".style2" +
                                  "{" +
                                  "width: 159px;" +
                                  "}" +
                                  "</style>" +
                                  "</head>" +
                                  "<body>" +
                                  "<form id=" + "form1" + "runat=" + "server" + ">" +
                                  "<div>" +
                                  "<table >" +

                                  "<tr>" +
                                  "<td class=" + "style1" + "></td>" +
                                  "<td class=" + "style2" + "></td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Firstname</td>" +
                                  "<td class=" + "style2" + ">" + firstName + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Middlename</td>" +
                                  "<td class=" + "style2" + ">" + middleName + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Lastname</td>" +
                                  "<td class=" + "style2" + ">" + lastName + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Date of Birth</td>" +
                                  "<td class=" + "style2" + ">" + dateOfBirth + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Phone1</td>" +
                                  "<td class=" + "style2" + ">" + phone1 + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Phone2</td>" +
                                  "<td class=" + "style2" + ">" + phone2 + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Email</td>" +
                                  "<td class=" + "style2" + ">" + email + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Employername</td>" +
                                  "<td class=" + "style2" + ">" + employerName + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Office Address 1</td>" +
                                  "<td class=" + "style2" + ">" + officeAddress1 + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Office Address 2</td>" +
                                  "<td class=" + "style2" + ">" + officeAddress2 + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + ">Office State</td>" +
                                  "<td class=" + "style2" + ">" + officeState + "</td>" +
                                  "</tr>" +

                                  "<tr>" +
                                  "<td class=" + "style1" + "></td>" +
                                  "<td class=" + "style2" + "></td>" +
                                  "</tr>" +
                                  "</table>" +
                                  "</div>" +
                                  "</form>" +
                                  "</body>" +
                                  "</html>";

            try
            {
                if (IsValid(receipient))
                {
                    emailSender.Send();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                flag = false;
            }

            try
            {
                using (SqlConnection sqlConn = new SqlConnection(connString))
                {
                    sqlConn.Open();
                    SqlCommand sqlCmd = new SqlCommand("Insert Into LEG_PENSION_LEAD (firstname, middlename, lastname, dateofbirth, phone1,phone2,email,EmployerName, OfficeAddress1,OfficeAddress2,OfficeState) select @FirstName, @MiddleName, @LastName, @DateOfBirth, @Phone1, @Phone2, @Email,@EmployerName @OfficeAddress1,@OfficeAddress2, @OfficeState");
                    sqlCmd.Connection = sqlConn;
                    sqlCmd.Parameters.AddWithValue("@firstname", firstName);
                    sqlCmd.Parameters.AddWithValue("@middlename", middleName);
                    sqlCmd.Parameters.AddWithValue("@lastname", lastName);
                    sqlCmd.Parameters.AddWithValue("@dateofbirth", dateOfBirth);
                    sqlCmd.Parameters.AddWithValue("@phone1", phone1);
                    sqlCmd.Parameters.AddWithValue("@phone2", phone2);
                    sqlCmd.Parameters.AddWithValue("@email", email);
                    sqlCmd.Parameters.AddWithValue("@EmployerName", employerName);
                    sqlCmd.Parameters.AddWithValue("@OfficeAddress1", officeAddress1);
                    sqlCmd.Parameters.AddWithValue("@OfficeAddress2", officeAddress2);
                    sqlCmd.Parameters.AddWithValue("@OfficeState", officeState);
                    sqlCmd.BeginExecuteNonQuery();
                    flag = true;
                }
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return(flag);
        }
Пример #57
0
        public async Task SendEmailAsync(EmailMessage message)
        {
            // impelemnt  with email service.

            return;
        }
        public async Task <APIResponse> Register(RegisterParameters parameters)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(new APIResponse(400, "User Model is Invalid"));
                }

                // https://gooroo.io/GoorooTHINK/Article/17333/Custom-user-roles-and-rolebased-authorization-in-ASPNET-core/32835
                string[]       roleNames = { "SuperAdmin", "Admin", "User" };
                IdentityResult roleResult;

                foreach (var roleName in roleNames)
                {
                    //creating the roles and seeding them to the database
                    var roleExist = await _roleManager.RoleExistsAsync(roleName);

                    if (!roleExist)
                    {
                        roleResult = await _roleManager.CreateAsync(new IdentityRole <Guid>(roleName));
                    }
                }

                var user = new ApplicationUser
                {
                    UserName = parameters.UserName,
                    Email    = parameters.Email
                };

                user.UserName = parameters.UserName;
                var result = await _userManager.CreateAsync(user, parameters.Password);

                if (!result.Succeeded)
                {
                    return(new APIResponse(400, "Register User Failed: " + result.Errors.FirstOrDefault()?.Description));
                }


                //Role - Here we tie the new user to the "Admin" role
                await _userManager.AddToRoleAsync(user, "Admin");

                if (Convert.ToBoolean(_configuration["RequireConfirmedEmail"]))
                {
                    #region New  User Confirmation Email
                    try
                    {
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        string callbackUrl = string.Format("{0}/Account/ConfirmEmail/{1}?token={2}", _configuration["ApplicationUrl"], user.Id, token);

                        var email = new EmailMessage();
                        email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
                        email = EmailTemplates.BuildNewUserConfirmationEmail(email, user.UserName, user.Email, callbackUrl, user.Id.ToString(), token); //Replace First UserName with Name if you want to add name to Registration Form

                        _logger.LogInformation("New user registered: {0}", user);
                        await _emailService.SendEmailAsync(email);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogInformation("New user email failed: {0}", ex.Message);
                    }
                    #endregion
                    return(new APIResponse(200, "Register User Success"));
                }

                #region New  User Email
                try
                {
                    var email = new EmailMessage();
                    email.ToAddresses.Add(new EmailAddress(user.Email, user.Email));
                    email = EmailTemplates.BuildNewUserEmail(email, user.UserName, user.Email, parameters.Password); //Replace First UserName with Name if you want to add name to Registration Form

                    _logger.LogInformation("New user registered: {0}", user);
                    await _emailService.SendEmailAsync(email);
                }
                catch (Exception ex)
                {
                    _logger.LogInformation("New user email failed: {0}", ex.Message);
                }
                #endregion

                return(await Login(new LoginParameters
                {
                    UserName = parameters.UserName,
                    Password = parameters.Password
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError("Register User Failed: {0}", ex.Message);
                return(new APIResponse(400, "Register User Failed"));
            }
        }
        public static void SendServerEmail(string token, string serverUrl, string organizationId, EmailMessage emailMessage, List <string> attachments, string accountName, string apiVersion)
        {
            var apiInstance = new EmailsApi(serverUrl);

            apiInstance.Configuration.AccessToken = token;

            try
            {
                var emailMessageJson = JsonConvert.SerializeObject(emailMessage);

                if (attachments != null)
                {
                    List <SystemFile.FileStream> attachmentsList = new List <SystemFile.FileStream>();

                    foreach (var attachment in attachments)
                    {
                        SystemFile.FileStream _file = new SystemFile.FileStream(attachment, SystemFile.FileMode.Open, SystemFile.FileAccess.Read);
                        attachmentsList.Add(_file);
                    }

                    apiInstance.ApiVapiVersionEmailsSendPostAsyncWithHttpInfo(apiVersion, organizationId, emailMessageJson, attachmentsList, accountName).Wait();

                    foreach (var file in attachmentsList)
                    {
                        file.Flush();
                        file.Dispose();
                        file.Close();
                    }
                }
                else
                {
                    apiInstance.ApiVapiVersionEmailsSendPostAsyncWithHttpInfo(apiVersion, organizationId, emailMessageJson, null, accountName).Wait();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message != "One or more errors occurred.")
                {
                    throw new InvalidOperationException("Exception when calling EmailsApi.SendEmail: " + ex.Message);
                }
                else
                {
                    throw new InvalidOperationException(ex.InnerException.Message);
                }
            }
        }
Пример #60
0
        /// <summary>
        /// Creates and tries to send three email messages with one call to EWS. The third email message intentionally fails
        /// to demonstrate how EWS returns errors for batch requests.
        /// </summary>
        /// <param name="service">A valid ExchangeService object with credentials and the EWS URL.</param>
        static void SendBatchEmails(ExchangeService service)
        {
            // Create three separate email messages.
            EmailMessage message1 = new EmailMessage(service);

            message1.ToRecipients.Add("*****@*****.**");
            message1.ToRecipients.Add("*****@*****.**");
            message1.Subject = "Status Update";
            message1.Body    = "Project complete!";

            EmailMessage message2 = new EmailMessage(service);

            message2.ToRecipients.Add("*****@*****.**");
            message2.Subject    = "High priority work items";
            message2.Importance = Importance.High;
            message2.Body       = "Finish estimate by EOD!";

            EmailMessage message3 = new EmailMessage(service);

            message3.BccRecipients.Add("*****@*****.**");
            message3.BccRecipients.Add("user2contoso.com"); // Invalid email address format.
            message3.Subject = "Surprise party!";
            message3.Body    = "Don't tell anyone. It will be at 6:00 at Aisha's house. Shhh!";
            message3.Categories.Add("Personal Party");

            Collection <EmailMessage> msgs = new Collection <EmailMessage>()
            {
                message1, message2, message3
            };

            try
            {
                // Send the batch of email messages. This results in a call to EWS. The response contains the results of the batched request to send email messages.
                ServiceResponseCollection <ServiceResponse> response = service.CreateItems(msgs, WellKnownFolderName.Drafts, MessageDisposition.SendOnly, null);

                // Check the response to determine whether the email messages were successfully submitted.
                if (response.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("All email messages were successfully submitted");
                    return;
                }

                int counter = 1;

                /* If the response was not an overall success, access the errors.
                 * Results are returned in the order that the action was submitted. For example, the attempt for message1
                 * will be represented by the first result since it was the first one added to the collection.
                 * Errors are not returned if an NDR is returned.
                 */
                foreach (ServiceResponse resp in response)
                {
                    Console.WriteLine("Result (message {0}): {1}", counter, resp.Result);
                    Console.WriteLine("Error Code: {0}", resp.ErrorCode);
                    Console.WriteLine("Error Message: {0}\r\n", resp.ErrorMessage);

                    counter++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }