示例#1
1
        public static void SendFormData(string ServerPath,HttpPostedFileBase[] files, string fileName, byte[] pdfArray, byte[] xmlArray)
        {
            var message = new EmailMessage(service)
            {
                Subject = fileName, 
                Body = fileName
            };
            message.ToRecipients.Add(ConfigurationManager.AppSettings["TargetMailBox"]);
            message.Attachments.AddFileAttachment(fileName + ".pdf", pdfArray);
            message.Attachments.AddFileAttachment(fileName + ".xml", xmlArray);

            try
            {
                /*Lopp for multiple files*/
                foreach (HttpPostedFileBase file in files)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    /*Saving the file in server folder*/
                    var path = System.IO.Path.Combine(ServerPath, filename);
                    message.Attachments.AddFileAttachment(path);
                    /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                }


            }
            catch
            {

            }

            message.Send();
        }
 private void SendEmailMessage(EmailMessage emailMessage, string internalID)
 {
     emailMessage.IsDeliveryReceiptRequested = true;
     emailMessage.IsReadReceiptRequested = true;
     emailMessage.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "InternalId", MapiPropertyType.String), internalID);
     emailMessage.SendAndSaveCopy();
 }
示例#3
0
        /// <summary>
        /// <see cref="RemoteProvider.CreateNewSyncItem"/>
        /// </summary>
        public override IRemoteItem CreateNewSyncItem(SyncItemSchema schema)
        {
            var value      = new Exchange.EmailMessage(Service);
            var remoteItem = new ExchangeEmailMessage(schema, value, TimeZone);

            return(remoteItem);
        }
示例#4
0
        public static void Transaction_CK_OrdersSendAlert()
        {
            try
            {
                var directory = new DirectoryInfo(zipPath);
                var myFile    = (from f in directory.GetFiles()
                                 orderby f.LastWriteTime descending
                                 select f).First();

                ExchangeService service  = new ExchangeService();
                string          from     = ConfigurationSettings.AppSettings["FromAddress"];
                string          frompass = ConfigurationSettings.AppSettings["FromPassword"];
                service.Credentials = new NetworkCredential(from, frompass);

                service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                EmailMessage message = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);
                message.Subject = ConfigurationSettings.AppSettings["MailSubject_CKOrder"] + strFileNameServiceDate + "";
                message.Body    = ConfigurationSettings.AppSettings["MailBody_CKOrder"] + strFileNameServiceDate + " excel";
                var path = System.IO.Path.Combine(directory + myFile.ToString());

                message.Attachments.AddFileAttachment(path);

                foreach (var address in ConfigurationSettings.AppSettings["ToAddressCK"].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.ToRecipients.Add(address);
                }
                message.Send();
            }
            catch (Exception ex)
            {
                SendAlertError(ex);
            }
        }
示例#5
0
        private static void SetMessageIsRead(EmailMessage message)
        {
            message.IsRead = true;
            message.Update(ConflictResolutionMode.AlwaysOverwrite);

            Console.WriteLine("Set this message status to readed");
        }
示例#6
0
        public EWSIncomingMessage(EmailMessage message)
        {
            _message = message;

            message.Load(new PropertySet(
                    ItemSchema.Subject,
                    ItemSchema.Body,
                    EmailMessageSchema.ConversationIndex,
                    EmailMessageSchema.Sender,
                    EmailMessageSchema.From,
                    EmailMessageSchema.ToRecipients,
                    EmailMessageSchema.CcRecipients,
                    ItemSchema.MimeContent,
                    ItemSchema.DateTimeReceived,
                    ItemSchema.DateTimeSent,
                    EmailMessageSchema.ConversationTopic,
                    ItemSchema.Attachments,
                    ItemSchema.HasAttachments,
                    MeetingRequestSchema.Location,
                    MeetingRequestSchema.Start,
                    MeetingRequestSchema.End
                ));

            Attachments = BuildAttachmentList(message);
        }
 public EmailMessage(
     EWS.EmailMessage email,
     string body = null,
     IEmailAttachment[] attachments = null)
 {
     _email       = email;
     _body        = body;
     _attachments = attachments;
 }
示例#8
0
        public static void SendMailTest()
        {
            EmailMessage message = new EmailMessage(service);
            message.Subject = "integration testts";
            message.Body = "fkytfoyufoyfy";
            message.ToRecipients.Add(ConfigurationManager.AppSettings["TargetMailBox"]);


            message.Send();
        }
 public bool Send(string to, string subject, string body, string theme = null)
 {
     EmailMessage message = new EmailMessage(_service);
     message.ToRecipients.Add(new EmailAddress(to));
     message.Subject = subject;
     message.Body = body;
     message.From = System.Configuration.ConfigurationManager.AppSettings["Affine.Email.User"];
     message.Send();
     return true;
 }
示例#10
0
 /// <summary>
 /// Sends email message.
 /// </summary>
 /// <param name="exchangeEmailMessage">Prepared email message.</param>
 protected virtual void SendMessage(Exchange.EmailMessage exchangeEmailMessage)
 {
     try {
         exchangeEmailMessage.SendAndSaveCopy(Exchange.WellKnownFolderName.SentItems);
     } catch (Exception e) {
         Info(string.Format("[ExchangeClient: {0} - {1}] Error on send message \"{2}\", {3}", _userConnection.CurrentUser.Name,
                            exchangeEmailMessage.From, exchangeEmailMessage.Subject, e.ToString()));
         throw;
     }
 }
示例#11
0
        public static void SendConfirmationEmail(string address, Guid formId, DateTime fileDate)
        {
            var message = new EmailMessage(service)
            {
                Subject = EmailResources.ConfirmationMailHeader,
                Body = String.Format(EmailResources.ConfirmationMailBody, fileDate.ToString(CultureInfo.GetCultureInfo("cs-Cz")), formId)
            };
            message.ToRecipients.Add(address);           

            message.Send();
        }
示例#12
0
        public MailRequest(EmailMessage msg)
        {
            this.From = msg.From.Address;
            this.To = msg.ToRecipients.First().Address;
            this.Subject = msg.Subject;
            this.Body = msg.Body;
            this.OriginalMessage = msg;

            msg.Load(new PropertySet(ItemSchema.MimeContent));
            this.FileFormat = msg.MimeContent.Content;

        }
示例#13
0
        static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Error.WriteLine("Usage: mail [email protected] subject");
                return 1;
            }

            try
            {
                string account = System.Environment.GetEnvironmentVariable("EMAIL");
                if (account == null)
                {
                    Console.Error.WriteLine("Set an environment variable called EMAIL with YOUR e-mail address.");
                    return 2;
                }

                string message = ReadStdin();
                if (message.Length == 0)
                {
                    Console.Error.WriteLine("No mail sent since stdin was empty.");
                    return 3;
                }

                Console.WriteLine("Sending e-mail using account '{0}'", account);
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(account, "");
                service.UseDefaultCredentials = true;

                // For verbose logging
                /*service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;*/

                service.AutodiscoverUrl(account, RedirectionUrlValidationCallback);

                EmailMessage email = new EmailMessage(service);
                email.ToRecipients.Add(args[0]);
                email.Subject = args[1];
                message = message.Replace("\n", "<br/>\n");
                email.Body = new MessageBody(message);

                email.Send();
                Console.WriteLine("Email successfully sent to '{0}'", args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return 4;
            }

            return 0;
        }
示例#14
0
 //Функция отправки сообщений на Email
 public Task SendEmail(string GetEmail, string mailSubject, string mailBody)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Body = new Exchange.MessageBody(mailBody);
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
示例#15
0
 //Функция отправки сообщений на Email
 public static Task SendEmail(string GetEmail, string itemName)
 {
     return(Task.Run(() =>
     {
         Exchange.ExchangeService service = new Exchange.ExchangeService();
         service.Credentials = new NetworkCredential(AppSettings.SendEmail, AppSettings.SendEmailPassword);
         service.AutodiscoverUrl(AppSettings.SendEmail);
         Exchange.EmailMessage emailMessage = new Exchange.EmailMessage(service);
         emailMessage.Subject = "Аукцион #ProКачка - Вы выиграли приз!";
         emailMessage.Body = new Exchange.MessageBody("Поздравляем, вы выиграли " + itemName + " на нашем аукционе #ProКачка.");
         emailMessage.ToRecipients.Add(GetEmail);
         emailMessage.Send();
     }));
 }
        public IHttpActionResult Send(SendEmailRequest request)
        {
            // Send Email
            var email = new EmailMessage(ExchangeServer.Open());

            email.ToRecipients.AddRange(request.Recipients);

            email.Subject = request.Subject;
            email.Body = new MessageBody(request.Body);


            email.Send();
            return Ok(new SendEmailResponse { Recipients = request.Recipients });
        }
        private static void SendMessages(ExchangeService service, ExchangeGeneratorParameters genParameters, ServerConnectionCredentials serverCreds, Random random1)
        {
            var email = new EmailMessage(service);

            email.ToRecipients.Add(genParameters.Recipient);
            email.Body = new MessageBody(HelperMethods.RandomString((int)genParameters.MessageSize,random1));
            email.Subject = "Exchange Generator (" + genParameters.MessageSize+")";

            var serviceRequestRetryCount = 0;
            var serviceResponseRetryCount = 0;

            while (true)
            {
                try
                {
                    email.Send();
                    break;
                }
                catch (ServiceRequestException e)
                {
                    if (serviceRequestRetryCount < 3)
                    {
                        serviceRequestRetryCount++;
                        Logger.Log("ServiceRequestException has been caught, retry in 15 seconds.", Logger.LogLevel.Warning, serverCreds.Ip);
                        Thread.Sleep(15000);

                    }
                    else
                    {
                        Logger.LogError("Something wrong with exchange server.", serverCreds.Ip, e);
                        throw;
                    }

                }
                catch (ServiceResponseException e)
                {
                    if (serviceResponseRetryCount < 3)
                    {
                        serviceResponseRetryCount++;
                        Logger.Log("ServiceResponseException has been caught, retry in 15 seconds.", Logger.LogLevel.Warning, serverCreds.Ip);
                        Thread.Sleep(15000);
                    }
                    else
                    {
                        Logger.LogError("Something wrong with exchange server.", serverCreds.Ip, e);
                        throw;
                    }
                }
            }
        }
示例#18
0
 /// <summary>
 /// Preparing email by <paramref name="emailMessage"/> data and send it.</summary>
 /// <param name="emailMessage">Email message data.</param>
 /// <param name="ignoreRights">Flag that indicates whether to ignore rights.</param>
 public void Send(EmailMessage emailMessage, bool ignoreRights)
 {
     Info(string.Format("[ExchangeClient: {0} - {1}] Start sending message \"{2}\"", _userConnection.CurrentUser.Name,
                        emailMessage.From, emailMessage.Subject));
     Exchange.EmailMessage exchangeEmailMessage = CreateExchangeEmailMessage(emailMessage, ignoreRights);
     Info(string.Format("[ExchangeClient: {0} - {1}] Exchange item for message \"{2}\" created", _userConnection.CurrentUser.Name,
                        emailMessage.From, emailMessage.Subject));
     exchangeEmailMessage.SetExtendedProperty(_exchangeUtility.GetContactExtendedPropertyDefinition(),
                                              _userConnection.CurrentUser.ContactId.ToString());
     Info(string.Format("[ExchangeClient: {0} - {1}] Exchange ExtendedProperty for message \"{2}\" created", _userConnection.CurrentUser.Name,
                        emailMessage.From, emailMessage.Subject));
     SendMessage(exchangeEmailMessage);
     Info(string.Format("[ExchangeClient: {0} - {1}] Exchange item for message \"{2}\" sended", _userConnection.CurrentUser.Name,
                        emailMessage.From, emailMessage.Subject));
 }
示例#19
0
        /// <summary>
        /// Creates <see cref="Exchange.EmailMessage"/> instance using data from <paramref name="bpmEmailMessage"/>.
        /// </summary>
        /// <param name="bpmEmailMessage">Email message instance.</param>
        /// <returns><see cref="Exchange.EmailMessage"/> instance.</returns>
        private Exchange.EmailMessage GetMessageInstance(EmailMessage bpmEmailMessage)
        {
            string emailAddress         = bpmEmailMessage.From.ExtractEmailAddress();
            var    importance           = GetExchangeImportance(bpmEmailMessage.Priority);
            var    exchangeEmailMessage = new Exchange.EmailMessage(Service)
            {
                Subject    = bpmEmailMessage.Subject,
                Body       = StringUtilities.ReplaceInvalidXmlChars(bpmEmailMessage.Body),
                Importance = importance,
                From       = emailAddress,
            };

            exchangeEmailMessage.Body.BodyType = bpmEmailMessage.IsHtmlBody ? Exchange.BodyType.HTML : Exchange.BodyType.Text;
            return(exchangeEmailMessage);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExchangeEmailMessage" /> class.
        /// </summary>
        /// <param name="email">The <see cref="ExchangeMessage" /> retrieved from the Exchange server.</param>
        /// <exception cref="ArgumentNullException"><paramref name="email" /> is null.</exception>
        internal ExchangeEmailMessage(ExchangeMessage email)
        {
            if (email == null)
            {
                throw new ArgumentNullException(nameof(email));
            }

            ExchangeId       = email.Id;
            DateTimeSent     = email.DateTimeSent;
            DateTimeReceived = email.DateTimeReceived;
            Subject          = email.Subject;
            Body             = email.Body;

            if (!string.IsNullOrEmpty(email.From?.Address))
            {
                try
                {
                    FromAddress = new MailAddress(email.From?.Address, email.From?.Name);
                }
                catch (FormatException)
                {
                    // Invalid From address.
                }
            }

            foreach (EmailAddress toRecipient in email.ToRecipients)
            {
                ToRecipients.Add(new MailAddress(toRecipient.Address, toRecipient.Name));
            }

            foreach (EmailAddress ccRecipient in email.CcRecipients)
            {
                CcRecipients.Add(new MailAddress(ccRecipient.Address, ccRecipient.Name));
            }

            if (email.HasAttachments)
            {
                foreach (FileAttachment file in email.Attachments)
                {
                    Attachments.Add(new ExchangeEmailAttachment(file));
                }
            }

            foreach (var header in email.InternetMessageHeaders)
            {
                Headers[header.Name] = header.Value;
            }
        }
        /// <summary>
        /// Retrieves up to the specified number email messages from the specfied <see cref="EmailFolder" />.
        /// </summary>
        /// <param name="folder">The <see cref="EmailFolder" /> to retrieve from.</param>
        /// <param name="itemLimit">The maximum number of messages to retrieve.</param>
        /// <returns>A collection of <see cref="EmailMessage" /> objects.</returns>
        public Collection <EmailMessage> RetrieveMessages(EmailFolder folder, int itemLimit)
        {
            Collection <EmailMessage> messages = new Collection <EmailMessage>();

            UpdateStatus($"Retrieving {folder} messages for {UserName}.", true);

            List <Item> items = RetrieveHeaders(folder, itemLimit).ToList();

            if (items.Any())
            {
                UpdateStatus($"Total email messages found: {items.Count}", true);

                // If the inbox has thousands of emails, then we will timeout waiting to download them all.
                // Work on this in batches.
                const int batchSize = 10;
                for (int i = 0; i < items.Count; i += batchSize)
                {
                    // Read in the next batch.
                    List <Item> batch = new List <Item>();
                    for (int j = 0; j < batchSize && (i + j) < items.Count; j++)
                    {
                        batch.Add(items[i + j]);
                    }

                    UpdateStatus($"Retrieving email messages from {i} to {i + batch.Count} (total {items.Count})");
                    PropertySet messageProperties = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments);
                    var         serviceResponses  = _service.LoadPropertiesForItems(batch, messageProperties);
                    UpdateStatus("Messages retrieved.");

                    foreach (GetItemResponse response in serviceResponses)
                    {
                        ExchangeMessage message = response.Item as ExchangeMessage;
                        try
                        {
                            messages.Add(new ExchangeEmailMessage(message));
                        }
                        catch (ServiceObjectPropertyException)
                        {
                            // This error can be thrown when the EmailMessage is an automated email sent from the Exchange server,
                            // such as a notification that the inbox is full. It may not contain all the properties of a normal email.
                            LogWarn($"Found invalid email with subject: {message.Subject}");
                        }
                    }
                }
            }
            return(messages);
        }
示例#22
0
 private Exchange.EmailMessage SetAttachments(Exchange.EmailMessage emailMessage,
                                              IEnumerable <EmailAttachment> attachments)
 {
     foreach (EmailAttachment attachment in attachments)
     {
         var newAttachment = emailMessage.Attachments.AddFileAttachment(attachment.Name, attachment.Data);
         if (attachment.IsContent)
         {
             newAttachment.ContentId = attachment.Id.ToString();
             if (emailMessage.Body.Text.Contains("cid:" + attachment.Id))
             {
                 ActivityUtils.SetInlineFlagAtActivityFile(_userConnection, attachment.Id);
             }
         }
     }
     return(emailMessage);
 }
示例#23
0
 /// <summary>
 /// Fills <paramref name="exchangeEmailMessage"/> recipients properties.
 /// </summary>
 /// <param name="exchangeEmailMessage"><see cref="Exchange.EmailMessage"/> instance.</param>
 /// <param name="bpmEmailMessage">Email message instance.</param>
 /// <returns><see cref="Exchange.EmailMessage"/> instance.</returns>
 private Exchange.EmailMessage SetRecipients(Exchange.EmailMessage exchangeEmailMessage, EmailMessage bpmEmailMessage)
 {
     foreach (var recipient in bpmEmailMessage.To)
     {
         exchangeEmailMessage.ToRecipients.Add(recipient.ExtractEmailAddress());
     }
     foreach (var recipient in bpmEmailMessage.Cc)
     {
         exchangeEmailMessage.CcRecipients.Add(recipient.ExtractEmailAddress());
     }
     foreach (var recipient in bpmEmailMessage.Bcc)
     {
         exchangeEmailMessage.BccRecipients.Add(recipient.ExtractEmailAddress());
     }
     Info(string.Format("[ExchangeClient: {0} - {1}] Message \"{2}\" recipients added", _userConnection.CurrentUser.Name,
                        bpmEmailMessage.From, bpmEmailMessage.Subject));
     return(exchangeEmailMessage);
 }
示例#24
0
        public MailMsg(EmailMessage msg, string user)
        {
            this._User = user;
            this._id = msg.Id.ToString();
            timestamp = msg.DateTimeSent;
            this._Subject = msg.Subject;
            this._Body = msg.Body;

            if (msg.HasAttachments)
            {
                //we will add all attachements to a list
                List<Attachement> oList = new List<Attachement>();
                //load all attachements
                msg.Load(new Microsoft.Exchange.WebServices.Data.PropertySet(Microsoft.Exchange.WebServices.Data.EmailMessageSchema.Attachments));
                foreach (Microsoft.Exchange.WebServices.Data.Attachment att in msg.Attachments)
                {
                    if (att is Microsoft.Exchange.WebServices.Data.FileAttachment)
                    {
                        //load the attachement
                        Microsoft.Exchange.WebServices.Data.FileAttachment fileAttachment = att as Microsoft.Exchange.WebServices.Data.FileAttachment;
                        //load into memory stream, seems the only stream supported
                        System.IO.MemoryStream ms = new System.IO.MemoryStream(att.Size);
                        fileAttachment.Load(ms);//blocks some time
                        ms.Position = 0;
                        oList.Add(new Attachement(ms, fileAttachment.Name));
                        ms.Close();
                    }
                }
                /*
                foreach (Attachment a in msg.Attachments)
                {
                    if (a is Microsoft.Exchange.WebServices.Data.FileAttachment)
                    {
                        FileAttachment fa = a as FileAttachment;
                        System.IO.MemoryStream ms=new System.IO.MemoryStream(fa.Size);
                        fa.Load(ms);
                        oList.Add(new Attachement(ms, fa.Name));
                    }
                }
                */
                this._Attachements = oList.ToArray();
                this.attList.AddRange(oList);
            }
        }
示例#25
0
        public static void SendNotiifcationEmail(string emailBody, List<string> recepients)
        {
            try
            {
                string rootUrl = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
                // Create a new Exchange service object
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                StringBuilder sbUserStatus = new StringBuilder();
                string ExchangeServerEmail = ConfigurationManager.AppSettings["ExchangeServerEmailID"];
                string ExchangeServerpwd = ConfigurationManager.AppSettings["ExchangeServerpwd"];
                foreach (string toEmail in recepients)
                {
                    string encryptedEmail = EncryptionUtility.Encrypt(toEmail);
                    string url = string.Format(rootUrl + "Usersettings/Unsubscribe?validateToken={0}", encryptedEmail);
                    emailBody = emailBody.Replace("{unsubribelink}", url);
                    // Set user login credentials
                    service.Credentials = new WebCredentials(ExchangeServerEmail, ExchangeServerpwd);
                    try
                    {
                        //Set Office 365 Exchange Webserivce Url
                        string serviceUrl = "https://outlook.office365.com/ews/exchange.asmx";
                        service.Url = new Uri(serviceUrl);
                        EmailMessage emailMessage = new EmailMessage(service);
                        emailMessage.Subject = "PnP TestAutomation daily summary report";
                        emailMessage.Body = new MessageBody(BodyType.HTML, emailBody);
                        emailMessage.ToRecipients.Add(toEmail);
                        //emailMessage.BccRecipients.Add(toEmail);
                        emailMessage.Send();

                    }
                    catch (AutodiscoverRemoteException exception)
                    {
                        Console.WriteLine("Erroe while sending the mails to user" + toEmail + exception.Message);
                        throw;

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erroe while sending the mails to users" + ex.Message);
            }
        }
        private EmailMessage GetMail(ProcessMessageArgs args, ExchangeService service)
        {
            var mail = new EmailMessage(service);

            if (args.To.Length > 0)
                args.To.ToString().Split(';').ToList().ForEach(emailAddress => mail.ToRecipients.Add(emailAddress));
            if (args.CC.Length > 0)
                args.CC.ToString().Split(';').ToList().ForEach(emailAddress => mail.CcRecipients.Add(emailAddress));
            if (args.BCC.Length > 0)
                args.BCC.ToString().Split(';').ToList().ForEach(emailAddress => mail.BccRecipients.Add(emailAddress));

            mail.Subject = args.Subject.ToString();

            mail.Body = args.Mail.ToString();

            args.Attachments.ForEach(attachment => mail.Attachments.AddFileAttachment(attachment.Name, attachment.ContentStream));

            return mail;
        }
示例#27
0
        /// <summary>
        /// Fills <paramref name="exchangeEmailMessage"/> headers collection using data from <paramref name="bpmEmailMessage"/>.
        /// </summary>
        /// <param name="exchangeEmailMessage"><see cref="Exchange.EmailMessage"/> instance.</param>
        /// <param name="bpmEmailMessage">Email message instance.</param>
        /// <returns><see cref="Exchange.EmailMessage"/> instance.</returns>
        private Exchange.EmailMessage SetHeaderProperties(Exchange.EmailMessage exchangeEmailMessage, EmailMessage bpmMessage)
        {
            List <EmailMessageHeader> headerProperties = bpmMessage.HeaderProperties;

            if (headerProperties != null)
            {
                foreach (var property in headerProperties)
                {
                    var header = new Exchange.ExtendedPropertyDefinition(Exchange.DefaultExtendedPropertySet.InternetHeaders,
                                                                         property.Name, Exchange.MapiPropertyType.String);
                    exchangeEmailMessage.SetExtendedProperty(header, property.Value);
                }
            }
            var PidTagInternetMessageId = new Exchange.ExtendedPropertyDefinition(_mapiMessageIdPropertyIdentifier,
                                                                                  Exchange.MapiPropertyType.String);

            exchangeEmailMessage.SetExtendedProperty(PidTagInternetMessageId, bpmMessage.GetMessageId());
            return(exchangeEmailMessage);
        }
示例#28
0
        /// <summary>
        /// <see cref="ExchangeSyncProvider.LoadSyncItem(SyncItemSchema,string)"/>
        /// </summary>
        public override IRemoteItem LoadSyncItem(SyncItemSchema schema, string id)
        {
            ExchangeBase remoteItem = null;

            Exchange.EmailMessage fullEmail = ExchangeUtility.SafeBindItem <Exchange.EmailMessage>(Service, new Exchange.ItemId(id));
            if (fullEmail != null)
            {
                remoteItem = new ExchangeEmailMessage(schema, fullEmail, TimeZone);
            }
            else
            {
                fullEmail  = new Exchange.EmailMessage(Service);
                remoteItem = new ExchangeEmailMessage(schema, fullEmail, id, TimeZone)
                {
                    State = SyncState.Deleted
                };
            }
            return(remoteItem);
        }
示例#29
0
        public void SendMail()
        {
            try
            {

                ExchangeService service = new ExchangeService();

                service.Credentials = new NetworkCredential("user", "pass", "banglalink");
                service.Url = new System.Uri(@"https://mail.banglalinkgsm.com/EWS/Exchange.asmx");
                service.AutodiscoverUrl("*****@*****.**");
                EmailMessage message = new EmailMessage(service);

                message.Subject = "Test Mail";
                message.Body = "Auto Generated Test Mail";
                message.ToRecipients.Add("*****@*****.**");

               // message.Attachments.AddFileAttachment("");
                message.Send();

                //ExchangeService service = new ExchangeService();
                //service.Credentials = new WebCredentials("onm_iss", "password", "banglalink"); ; //new NetworkCredential("OnMSharingDB", "password","banglalinkgsm");
                //service.AutodiscoverUrl("*****@*****.**");
                //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**");

                ////service.na
                //EmailMessage message = new EmailMessage(service);
                //message.From = "*****@*****.**";
                //message.Subject = "Test Mail";
                //message.Body = "Auto Generated Test Mail";
                //message.ToRecipients.Add("*****@*****.**");
                ////message.ToRecipients.Add("*****@*****.**");
                //message.Save();

                //message.SendAndSaveCopy();
                ////message.Send();

            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#30
0
        public static void SendAlertError(Exception ex)
        {
            string strBody = "Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                             "" + Environment.NewLine + "Date :" + DateTime.Now.ToString();
            ExchangeService service  = new ExchangeService();
            string          from     = ConfigurationSettings.AppSettings["FromAddress"];
            string          frompass = ConfigurationSettings.AppSettings["FromPassword"];

            service.Credentials = new NetworkCredential(from, frompass);

            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            EmailMessage message = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);

            message.Subject = "Error in tenaris order utility : " + ex.Message;
            message.Body    = strBody;
            foreach (var address in ConfigurationSettings.AppSettings["ToAddressErrorNotification"].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.ToRecipients.Add(address);
            }
            message.Send();
        }
        /// <summary>
        /// Sends the specified <see cref="MailMessage" /> through the email server.
        /// </summary>
        /// <param name="message">The <see cref="MailMessage" /> to send.</param>
        /// <param name="attachments">The attachments to include with the message.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="message" /> is null.
        /// <para>or</para>
        /// <paramref name="attachments" /> is null.
        /// </exception>
        public void Send(MailMessage message, IEnumerable <FileInfo> attachments)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (attachments == null)
            {
                throw new ArgumentNullException(nameof(attachments));
            }

            ExchangeMessage email = new ExchangeMessage(_service);

            email.Subject = message.Subject;
            email.Body    = message.Body;

            foreach (MailAddress toRecipient in message.To)
            {
                email.ToRecipients.Add(toRecipient.Address);
            }

            foreach (MailAddress ccRecipient in message.CC)
            {
                email.CcRecipients.Add(ccRecipient.Address);
            }

            foreach (FileInfo file in attachments)
            {
                email.Attachments.AddFileAttachment(file.FullName);
            }

            foreach (string key in message.Headers.AllKeys)
            {
                ExtendedPropertyDefinition headerDefinition = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, key, MapiPropertyType.String);
                email.SetExtendedProperty(headerDefinition, message.Headers[key]);
            }

            email.Send();
        }
示例#32
0
        /// <summary>
        /// Gets emails from <see cref="itemCollection"/>
        /// </summary>
        /// <param name="itemCollection">Finding list items from exchange.</param>
        /// <param name="activityFolderIds">List folders uniqueidentifier.</param>
        /// <returns></returns>
        public virtual IEnumerable <IRemoteItem> GetEmailsFromCollection(Exchange.FindItemsResults <Exchange.Item> itemCollection,
                                                                         List <Guid> activityFolderIds)
        {
            SyncItemSchema schema = FindSchemaBySyncValueName(typeof(ExchangeEmailMessage).Name);

            foreach (Exchange.Item item in itemCollection)
            {
                if (item is Exchange.EmailMessage)
                {
                    Exchange.PropertySet  properties = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
                    Exchange.EmailMessage bindEmail  = ExchangeUtility.SafeBindItem <Exchange.EmailMessage>(Service, item.Id, properties);
                    if (bindEmail != null)
                    {
                        var remoteItem = new ExchangeEmailMessage(schema, bindEmail, TimeZone)
                        {
                            ActivityFolderIds = activityFolderIds
                        };
                        yield return(remoteItem);
                    }
                }
            }
        }
        public void Send(MailMessage message)
        {
            ex.EmailMessage exchangeMessage = new ex.EmailMessage(GetExchangeService(Username, Password));

            if (message.From != null && !string.IsNullOrEmpty(message.From.Address))
            {
                exchangeMessage.From = new ex.EmailAddress(message.From.Address);
            }
            else
            {
                exchangeMessage.From = new ex.EmailAddress(_config["NOME_CAIXA"]);
            }

            exchangeMessage.Subject = message.Subject;
            exchangeMessage.Body = new ex.MessageBody(message.IsBodyHtml ? ex.BodyType.HTML : ex.BodyType.Text, message.Body);

            foreach (var destinatario in message.To)
            {
                exchangeMessage.ToRecipients.Add(destinatario.Address);
            }

            foreach (var copia in message.CC)
            {
                exchangeMessage.CcRecipients.Add(copia.Address);
            }

            foreach (var copiaOculta in message.Bcc)
            {
                exchangeMessage.BccRecipients.Add(copiaOculta.Address);
            }
           
            foreach (Attachment attachment in message.Attachments)
            {
                exchangeMessage.Attachments.AddFileAttachment(attachment.Name);
            }

            exchangeMessage.Send();
        }
示例#34
0
        private static void IntegrateDdasIntoGdw(EmailMessage message)
        {
            foreach (Attachment attachment in message.Attachments)
            {
                if (attachment is FileAttachment)
                {
                    FileAttachment fileAttachment = attachment as FileAttachment;

                    var backFolderPath = AppSettings.BackupPath + DateTime.Now.ToString("yyyyMMdd") + "_" + message.Id + "\\";
                    var backFilePath = backFolderPath + fileAttachment.Name;

                    CopyFileFromAttachment(fileAttachment, backFolderPath);

                    DecompressFile(backFolderPath, backFilePath);

                    var destFileName = fileAttachment.Name.Replace(".zip", ".csv");
                    CopyFileToSharedFolder(destFileName, backFolderPath, message.From.Address);
                }
                else
                {
                    Console.WriteLine("There is a attachment which type is not FileAttachment");
                }
            }
        }
示例#35
0
        static void Main(string[] args)
        {
            try
            {
                var o = CommandLineParser.ParseCommandLine<Options>(args);

                var template = File.ReadAllText(o.Template);
                var maillist = ReadTsv(o.Maillist).ToList();

                var service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                NetworkCredential nc;
                Credential.GetCredentialsVistaAndUp("office365", out nc);
                service.Credentials = nc;
                if (o.TraceExchange)
                {
                    service.TraceEnabled = true;
                    service.TraceFlags = TraceFlags.All;
                }
                service.Url = new Uri(o.ExchangeServer);

                if (o.Preview && !Directory.Exists(o.PreviewDir))
                    Directory.CreateDirectory(o.PreviewDir);

                Regex r = new Regex(@"^\s*([^:]+):\s*(.*)$");
                int i = 0;
                foreach (var item in maillist)
                {
                    var mail = new EmailMessage(service);

                    var s = template;
                    foreach (var kvp in item)
                        s = s.Replace("[[" + kvp.Key + "]]", kvp.Value);

                    bool foundEmpty = false;
                    StringBuilder body = new StringBuilder();
                    foreach (var line in s.Split('\n'))
                    {
                        if (foundEmpty) { body.AppendLine(line); continue; }
                        if (string.IsNullOrWhiteSpace(line)) { foundEmpty = true; continue; }
                        var m = r.Match(line);
                        if (!m.Success) throw new Exception("bad header field " + line);
                        switch (m.Groups[1].Value.ToLowerInvariant())
                        {
                            case "subject": mail.Subject = m.Groups[2].Value.Trim(); break;
                            case "to": mail.ToRecipients.Add(m.Groups[2].Value.Trim()); break;
                            case "cc": mail.CcRecipients.Add(m.Groups[2].Value.Trim()); break;
                            case "bcc": mail.BccRecipients.Add(m.Groups[2].Value.Trim()); break;
                            case "attach": mail.Attachments.AddFileAttachment(m.Groups[2].Value.Trim()); break;

                            default:
                                throw new Exception("unknown field in template: " + m.Groups[1].Value);
                        }
                    }
                    mail.Body = body.ToString();

                    if (o.Preview)
                    {
                        using (var sw = new StreamWriter(Path.Combine(o.PreviewDir, string.Format("preview_{0}.html", ++i))))
                        {
                            sw.WriteLine("<pre>");
                            sw.WriteLine("Subject: " + mail.Subject);
                            foreach (var email in mail.ToRecipients)
                                sw.WriteLine("To: " + email.ToString());
                            foreach (var email in mail.CcRecipients)
                                sw.WriteLine("Cc: " + email.ToString());
                            foreach (var email in mail.BccRecipients)
                                sw.WriteLine("Bcc: " + email.ToString());
                            foreach (var attach in mail.Attachments)
                                sw.WriteLine("Attach: " + attach.Name);
                            sw.WriteLine("</pre>");
                            sw.WriteLine("<hr>");
                            sw.WriteLine(mail.Body);
                        }
                        continue;
                    }

                    mail.SendAndSaveCopy();
                }
            }
            catch (CommandLineParseError err)
            {
                Console.Error.WriteLine(err.Message);
                Console.Error.WriteLine(err.Usage);
                Environment.Exit(1);
            }
            catch (Exception exn)
            {
                Console.Error.WriteLine(exn.ToString());
                Environment.Exit(1);
            }
        }
示例#36
0
 private void sendEmail()
 {
     EmailMessage email = new EmailMessage(service);
     email.Subject = "Hello World!";
     email.ToRecipients.Add("*****@*****.**");
     email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API.");
     email.Send();
 }
示例#37
0
        public void SendUntrackMail(string from, string[] toList, string[] ccList, string body, string subject, string[] attachmentsPathList)
        {
            if (toList.Length > 0)
            {
                EmailMessage email = new EmailMessage(service);
                //email.From = new EmailAddress(from);
                email.Subject = subject;
                email.Body = body;

                if (null != toList)
                {
                    for (int i = 0; i < toList.Length; i++)
                    {
                        email.ToRecipients.Add(toList[i]);
                    }
                }

                if (null != ccList)
                {
                    for (int i = 0; i < ccList.Length; i++)
                    {
                        email.CcRecipients.Add(ccList[i]);
                    }
                }

                if (attachmentsPathList != null)
                {
                    for (int i = 0; i < attachmentsPathList.Length; i++)
                    {
                        email.Attachments.AddFileAttachment(attachmentsPathList[i]);
                    }
                }

                email.Send();
            }
        }
示例#38
0
        public bool SendEmail(string _Subject, string _Body, IList<EmailVO> _To, IList<EmailVO> _CC, int? _InternalId)
        {
            try
            {
                string internalId = "";

                if (_InternalId.HasValue)
                    internalId = _InternalId.Value.ToString();

                EmailMessage email = new EmailMessage(service);
                email.Subject = _Subject + string.Format(" (Email #:{0})", internalId);
                email.Body = _Body;

                for (int i = 0; i < _To.Count; i++)
                {
                    email.ToRecipients.Add(_To[i].Email);
                }

                for (int i = 0; i < _CC.Count; i++)
                {
                    email.CcRecipients.Add(_CC[i].Email);
                }

                SendEmailMessage(email, internalId);

                return true;
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("There was an error Sending the Email.!\n{0}\n{1}", ex.Message, ex.StackTrace));
                return false;
            }
        }
示例#39
0
        public bool SendEmail(string _Subject, string _Body, string _To, string _CC, int? _InternalId)
        {
            try
            {
                string[] toRecipients = _To.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string[] ccRecipients = _CC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                string internalId = "";

                if (_InternalId.HasValue)
                    internalId = _InternalId.Value.ToString();

                EmailMessage email = new EmailMessage(service);
                email.Subject = _Subject + string.Format(" (Email #:{0})", internalId);
                email.Body = _Body;
                email.Body.BodyType = BodyType.HTML;

                for (int i = 0; i < toRecipients.Length; i++)
                {
                    email.ToRecipients.Add(toRecipients[i]);
                }

                for (int i = 0; i < ccRecipients.Length; i++)
                {
                    email.CcRecipients.Add(ccRecipients[i]);
                }

                SendEmailMessage(email, internalId);

                return true;
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("There was an error Sending the Email.!\n{0}\n{1}", ex.Message, ex.StackTrace));
                return false;
            }
        }
示例#40
0
 public static string GetConversationIndex(EmailMessage message)
 {
     return string.Join("", message.ConversationIndex.Select(b => b.ToString("X2")));
 }
示例#41
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            string[] attachments = null;
            ClaimComment comment = null;
            string emailTo = txtEmailTo.Text.Trim().Replace(",", ";");
            string emailBody = null;
            string[] cc = null;
            string cc_list = null;
            string decryptedPassword = null;
            ArrayList documentArray = null;
            bool isSSL = true;
            int leadID = 0;
            int port = 0;
            string[] recipients = emailTo.Split(';');
            string subject = null;
            CRM.Data.Entities.SecUser user = null;

            Page.Validate("email");
            if (!Page.IsValid)
                return;

            // get user information
            user = SecUserManager.GetByUserId(SessionHelper.getUserId());

            if (user == null) {
                clearFields();
                return;
            }

            // decrypt user password
            decryptedPassword = Core.SecurityManager.Decrypt(user.emailPassword);

            // email CC
            if (!string.IsNullOrEmpty(txtEmailCC.Text)) {
                cc_list = txtEmailCC.Text.Replace(",", ";");

                cc = cc_list.Split(';');
            }

            // get attachments
            if (lbxDocuments != null && lbxDocuments.Items != null && lbxDocuments.Items.Count > 0) {
                documentArray = new ArrayList();

                foreach (ListItem item in lbxDocuments.Items) {
                    if (item.Selected) {
                        string documentPath = appPath + "/" + item.Value;

                        documentArray.Add(documentPath);
                    }
                }
                attachments = documentArray.ToArray(typeof(string)) as string[];
            }

            // add to comments

            int.TryParse(user.emailHostPort, out port);

            emailBody = string.Format("<div>{0}</div><div>{1}</div>", txtEmailText.Text.Trim(), txtSignature.Text.Trim());

            subject = txtEmailSubject.Text.Trim();

            //isSSL = user.isSSL ?? true;
            //string smtpHost = ConfigurationManager.AppSettings["smtpHost"].ToString();
            //int smtpPort = ConfigurationManager.AppSettings["smtpPort"] == null ? 25 : Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]);
            //string smtpEmail = ConfigurationManager.AppSettings["smtpEmail"].ToString();
            //string smtpPassword = ConfigurationManager.AppSettings["smtpPassword"].ToString();

            try {
               // Core.EmailHelper.sendEmail(txtEmailFrom.Text, recipients, cc, subject, emailBody, attachments, smtpHost, smtpPort, smtpEmail, smtpPassword, isSSL);
                userID = SessionHelper.getUserId();

                CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
                string emailaddress = secUser.Email;
                string password = SecurityManager.Decrypt(secUser.emailPassword);
                string url = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(emailaddress, password);
                service.Url = new Uri(url);

                EmailMessage email = new EmailMessage(service);

                foreach (var recipient in recipients)
                {
                    if (!string.IsNullOrEmpty(recipient))
                        email.ToRecipients.Add(recipient);
                }
                email.Subject = subject;
                email.Body = new MessageBody(emailBody);

                foreach (var filename in attachments)
                {
                    if (!string.IsNullOrEmpty(filename))
                        email.Attachments.AddFileAttachment(filename);
                }

                email.SendAndSaveCopy();
                comment = new ClaimComment();
                comment.ClaimID = this.claimID;
                comment.CommentDate = DateTime.Now;
                comment.CommentText = string.Format("Sent Email:<br/>To: {0}<br/>Subject: {1}<br/>{2}",
                                    txtEmailTo.Text.Trim(), txtEmailSubject.Text.Trim(), txtEmailText.Text.Trim());
                comment.IsActive = true;
                comment.UserId = this.userID;

                ClaimCommentManager.Save(comment);

                clearFields();

                lblMessage.Text = "Email sent successfully.";
                lblMessage.CssClass = "ok";
            }
            catch (Exception ex) {
                lblMessage.Text = "Incorrect Email Settings. Email not sent.";
                lblMessage.CssClass = "error";

                Core.EmailHelper.emailError(ex);
            }
        }
示例#42
0
        static void Main(string[] args)
        {
            var versionInf = new VersionInfo("old", "xref");

            Filter(versionInf);
            var content = GetConfig <BuildConfig>(@"C:\TestFiles\xrefmap\docfx.temp.json");
            var def     = BranchNames.DefaultBranches;
            var branch1 = MappingBranch("live-sxs");
            var ps      = Path.Combine("/", "/basepath", "ab");
            Uri uri;

            if (Uri.TryCreate("http://www.abc.com/base/a.html", UriKind.Relative, out uri))
            {
                Console.WriteLine("is relative");
            }
            var versionFolder = new VersionInfo("folder", null);

            File.WriteAllText(@"C:\TestFiles\xrefmap\filemap.now.json", JsonUtility.ToJsonString(versionFolder, true));
            var paths = new List <string> {
                "1", "2"
            };
            var joinedPath = string.Join(", ", paths);
            var dict       = new Dictionary <int, int>();

            dict.Add(0, 0);
            dict.Add(1, 1);
            dict.Add(2, 2);
            dict.Remove(0);
            dict.Add(10, 10);

            foreach (var entry in dict)
            {
                Console.WriteLine(entry.Key);
            }

            Dictionary <string, VersionInfo> versionInfo = new Dictionary <string, VersionInfo>
            {
                { "testMoniker-1.0_justfortest", new VersionInfo("v2.0/", null) },
                { "testMoniker-1.1_justfortest", new VersionInfo("v2.1/", null) }
            };

            var xrefmaps = new List <string>
            {
                "xrefmap.yml",
                "testMoniker-1.0_justfortest.xrefmap.yml",
                "testMoniker-1.1_justfortest.xrefmap.yml"
            };

            var defaultXrefMap = xrefmaps.FirstOrDefault(x => string.Equals(x, DefaultXrefMap, StringComparison.OrdinalIgnoreCase));

            var defaultVersionInfo = !string.IsNullOrEmpty(defaultXrefMap) ? new VersionInfo(string.Empty, defaultXrefMap) : null;

            var xrefmapsWithVersion = xrefmaps.Where(x => !string.IsNullOrEmpty(x) && x.EndsWith(XrefMapSuffix));

            foreach (var xrefmapWithVersion in xrefmapsWithVersion)
            {
                var escapedVersion = xrefmapWithVersion.Substring(0, xrefmapWithVersion.Length - XrefMapSuffix.Length);
                if (!string.IsNullOrEmpty(escapedVersion))
                {
                    var         unescapedversion = Uri.UnescapeDataString(escapedVersion);
                    VersionInfo versionInfoItem;
                    if (versionInfo.TryGetValue(unescapedversion, out versionInfoItem) && versionInfoItem != null)
                    {
                        versionInfoItem.XRefMap = xrefmapWithVersion;
                    }
                }
            }

            var branch = "live";

            myret(branch);
            Directory.CreateDirectory(@"c:\ab\c\text.txt");
            //webc.Get(new Uri("c:\\ab.txt"));
            var da  = new string[] { "1" };
            var fir = da.First(x => x == "2");

            foreach (var fi in fir)
            {
                Console.WriteLine("");
            }
            Digit <string[]> dig = new Digit <string[]>(da);

            //This call invokes the implicit "double" operator
            string[] num = dig;

            //string snu = null;
            //var tsnu = (string)snu;
            //var t1 = PrintAsync(1);
            //var t2 = PrintAsync(2);
            //var t3 = PrintAsync(3);
            //var t4 = PrintAsync(4);
            //var t5 = PrintAsync(5);
            //var tasks = new List<Task> { t1, t2, t3 };
            //TaskHelper.WhenAll(tasks, 2).Wait();
            var depots = new List <string> {
                "1", "4", "2", "3"
            };
            var allDepots = depots.Concat(new List <string> {
                "6"
            });
            var dep = fff(depots).Result;

            var orderDepots   = depots.OrderByDescending(depot => IsCurrentDepot("1", depot));
            var nr            = FileUtility.NormalizeRelativePath("test.txt");
            var de            = default(string);
            var manifestJson  = File.ReadAllText(@"C:\Users\ychenu\Downloads\2929183a-17190aeb%5C201708210354455948-master\testMultipleVersion\test.json");
            var buildManifest = JsonUtility.FromJsonString <BuildManifest>(manifestJson);

            foreach (var item in buildManifest.ItemsToPublish)
            {
                if (item.Type == PublishItemType.XrefMap)
                {
                    Console.WriteLine($"{item.RelativePath} is xrefmap");
                }
            }
            IEnumerable <string> itemss = new List <string> {
                "1.json", "2.json", "3.json"
            };
            var itemsss = itemss.ToList();

            itemss.GenerateMtaJsonFilesAsync().Wait();
            var filename = Path.ChangeExtension("test\\test.md", ".mta.json");

            JsonUtility.ToJsonFile(filename, "test");
            var combined   = Path.Combine("test\\index.md", ".mta.json");
            var loop       = TestLoop(3).ToList();
            var version    = "<abc>";
            var escapedata = Uri.EscapeDataString(version);
            var data       = Uri.UnescapeDataString(escapedata);
            Dictionary <string, List <string> > repoByKey = new Dictionary <string, List <string> >();

            repoByKey["key1"] = new List <string> {
                "1"
            };
            var repos = repoByKey["key1"];

            repos.Add("2");
            File.WriteAllLines(@"D:\Data\DataFix\FixLocRepoConfig\test.txt", new List <string> {
                "1", "2"
            });
            File.AppendText(@"D:\Data\DataFix\FixLocRepoConfig\test.txt");
            var now    = $"{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.log";
            var utcnow = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
            var pa     = Path.Combine(@"c:\test\testfile", "RepositoryTableData.json");
            var dir    = Path.GetDirectoryName(@"c:\test\testfile\abc.txt");

            Directory.CreateDirectory(dir);
            File.WriteAllText(@"c:\test\testfile\abc.txt", "test");
            var list        = new List <int> {
            };
            var filter      = list.Where(i => i == 3).ToList();
            var useAsync    = ConfigurationManager.AppSettings["UseAsync"];
            var parallelism = -1;

            int.TryParse(ConfigurationManager.AppSettings["Parallelism"], out parallelism);
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                Console.WriteLine("sleep for 5s");
            }).Wait();
            var herf = "api/System.Web.UI.MobileControls.MobileListItem.OnBubbleEvent.html#System_Web_UI_MobileControls_MobileListItem_OnBubbleEvent_System_Object_System_EventArgs_";
            var rep  = GetNormalizedFileReference(herf, string.Empty);
            var dic  = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            dic.Add("a", 1);
            dic.Add("A", 40);
            dic.Add("context", new Dictionary <string, object> {
                { "1", 3 }
            });
            var hash = Hash.FromDictionary(dic);

            Console.WriteLine("before WaitForSomething");
            WaitForSomething();
            Console.WriteLine("after WaitForSomething");
            AsyncAwaitDemo.Get().Wait();
            var ie = new string[] { }.Where(i => i == "");
            var jjj = string.Join(",", null);

            try
            {
                using (var reader = new StreamReader(@"C:\TestFiles\log.json"))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        var logItem = JsonUtility.FromJsonString <LogItem>(line);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            var directory  = @"C:\Git\OpenPublishing.Build";
            var extensions = new string[] { ".config", ".csproj" };
            var oldVersion = "2.19.0-alpha-0681-g405ed2d";
            var newVersion = "2.19.0";

            UpdatePackageVersion.Update(directory, extensions, oldVersion, newVersion);
            Convert.ToBoolean("s");
            bool result;

            if (bool.TryParse(null, out result))
            {
                var ssss = result;
            }
            var sbtest = new StringBuilder();

            testsb(sbtest);
            sbtest.AppendLine("out of testsb");
            Console.WriteLine(sbtest.ToString());
            var silent = false;

            try
            {
                throw new FileNotFoundException("");
            }
            catch (Exception) when(silent)
            {
                Console.WriteLine("catch");
            }

            var li = new List <int> {
                1, 2
            };
            var second = new List <int> {
                3, 2
            };
            var exc = li.Except(second);

            li.Add(1);
            li.Add(1);
            var permission = OpsPermission.ReadOnly;

            permission |= OpsPermission.MonikerAdmin;
            var re = new int[] { 1 }.Where(x => x == 3);
            var co = re.Count();
            CancellationTokenSource cts = new CancellationTokenSource();
            ParallelOptions         po  = new ParallelOptions();

            po.CancellationToken = cts.Token;

            Task.Factory.StartNew(() =>
            {
                if (Console.ReadKey().KeyChar == 'c')
                {
                    cts.Cancel();
                }
                Console.WriteLine("press any key to exit");
            });

            Parallel.ForEach(new List <int>(), po, (algo) =>
            {
                Task.Delay(2000).Wait(); // this compute lasts 1 minute
                Console.WriteLine("this job is finished");
                po.CancellationToken.ThrowIfCancellationRequested();
            });

            try
            {
                Task.Run(() =>
                {
                    for (var i = 0; i < 100; ++i)
                    {
                        throw new Exception("throw from run");
                    }
                });
            }
            catch (AggregateException aex)
            {
                Console.WriteLine("aex");
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex");
            }

            var exchangeSvc = new MsExchange.ExchangeService(MsExchange.ExchangeVersion.Exchange2010)
            {
                Url          = new Uri("https://outlook.office365.com/ews/exchange.asmx"),
                Credentials  = new MsExchange.WebCredentials("*****@*****.**", "#Bugsfor$-160802"),
                TraceEnabled = true
            };

            var message = new MsExchange.EmailMessage(exchangeSvc);

            message.ToRecipients.Add("*****@*****.**");

            message.Subject = "test";
            message.Body    = "test body";

            message.Save();
            message.Send();

            CreateOrUpdateDocument("abc_id", 6,
                                   new CreateOrUpdateDocumentRequest
            {
                ContentSourceUri = null,
                Metadata         = new Dictionary <string, object>
                {
                    { "assetId", "s" },
                    { "d", 7 }
                }
            });
            var name   = $"{nameof(args)}.{nameof(args.Rank)}";
            var ar     = new int[] { 6, 7, 3 };
            var sortAr = ar.OrderByDescending(x => x);

            try
            {
                var fo    = $"{"a"}{null}";
                var items = new List <Item>
                {
                    new Item {
                        Version = "v1", Url = "d"
                    },
                    new Item {
                        Version = "v1", Url = "b"
                    },
                    new Item {
                        Version = "v1", Url = "c"
                    },
                    new Item {
                        Version = "v2", Url = "f"
                    },
                    new Item {
                        Version = "v2", Url = "a"
                    }
                };

                var web = new HtmlWeb()
                {
                    //PreRequest = request =>
                    //{
                    //    // Make any changes to the request object that will be used.
                    //    request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                    //    return true;
                    //}
                };
                var document = web.Load(@"https://opdhsblobsandbox01.blob.core.windows.net/contents/0ced3babc6274b949a9696c03ed9d944/3094b7719e20479798997b70294c9ee3");
                FolderUtility.ForceDeleteAllSubDirectories(@"C:\TestFiles\Test", 1);
            }
            catch (AggregateException aex)
            {
                Console.WriteLine("aex");
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex");
            }
            var array = new Task[] { };
            var f     = array.FirstOrDefault();

            Array.ForEach(array, ele =>
            {
                Console.WriteLine(ele);
            });
            var commentSb = new StringBuilder();

            for (int j = 0; j < 2; j++)
            {
                commentSb.AppendFormat(" [View]({0})", "path" + j);
                commentSb.Append("<br/>");
            }

            commentSb.Length -= "<br/>".Length;

            commentSb.AppendLine(@"
File | Status | Preview URL | Details
---- | ------ | ----------- | -------");

            for (int i = 0; i < 2; i++)
            {
                commentSb.AppendFormat(
                    "[{0}]({1}) | {2} |",
                    "path" + i,
                    "http://abc" + i,
                    "success");

                var sb = new StringBuilder();
                for (int j = 0; j < 2; j++)
                {
                    commentSb.AppendFormat(" [View]({0})", "path" + j);
                    if (j == 0)
                    {
                        commentSb.AppendFormat("({0})", j);
                    }
                    commentSb.Append("<br/>");
                }

                commentSb.AppendFormat(" |");

                commentSb.AppendFormat(" [Details](#user-content-{0})", "details");

                commentSb.AppendLine();
            }

            var strsb = commentSb.ToString();

            File.WriteAllText(@"C:\TestFiles\comment.md", strsb);

            //var derived = new DerivedPackageDownloadAndUnzipPathInfo();
            string source = null;

            Console.WriteLine($"{source}-abc");
            var packageTypeToPathsMap = new Dictionary <BlobPackageType, PackageDownloadAndUnzipPathInfo>();

            var skipPackageDownloadingMap = new Dictionary <BlobPackageType, bool>();

            skipPackageDownloadingMap[BlobPackageType.Source] = true;
            skipPackageDownloadingMap[BlobPackageType.Cache]  = true;
            var skip = JsonUtility.ToJsonString(skipPackageDownloadingMap);
            var packageTypeToSkipFlagMap = JsonUtility.FromJsonString <Dictionary <BlobPackageType, bool> >(skip);

            foreach (var packageTypeToSkipFlagKeyValuePair in packageTypeToSkipFlagMap)
            {
                var blobPackageType        = packageTypeToSkipFlagKeyValuePair.Key;
                var skipPackageDownloading = packageTypeToSkipFlagKeyValuePair.Value;
                //if (!skipPackageDownloading)
                {
                    var packageBlobDownloadPath = packageTypeToPathsMap[blobPackageType].PackageBlobDownloadPath;
                }
            }
            var path = Path.GetTempPath();

            try
            {
                var details = "data ex";
                throw new InvalidDataException($"invalid {details}");
            }
            catch (InvalidDataException idex)
            {
                Console.WriteLine($"data ex: {idex}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("ex");
            }
            var workingDirectory = Path.Combine(@"c:\users\ychenu", Path.GetRandomFileName().Substring(0, 4));
            var work             = new Work();
        }
示例#43
0
        protected void ExchangeSend()
        {
            try
            {
                //String eMailExchange = System.Configuration.ConfigurationSettings.AppSettings.Get("MailExchange");
                String username = System.Configuration.ConfigurationManager.AppSettings["ExchangeUsername"];
                String password = System.Configuration.ConfigurationManager.AppSettings["ExchangePassword"];
                String domain = System.Configuration.ConfigurationManager.AppSettings["ExchangeDomain"];

                //ExchangeService service = new ExchangeService();
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                //service.AutodiscoverUrl(eMailExchange);
                service.Credentials = new WebCredentials(username, password, domain);
                service.Url = new Uri("https://mail.cn.ab-inbev.com/EWS/Exchange.asmx");

                EmailMessage message = new EmailMessage(service);
                message.Subject = Subject;
                message.Body = Content;
                message.ToRecipients.AddRange(EmailAddresses);
                message.Save();

                message.SendAndSaveCopy();
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);

            }
        }
示例#44
0
        private void EwsTest_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(UserName.Text) || string.IsNullOrEmpty(Psw.Text) ||
                string.IsNullOrEmpty(DomainName.Text) ||
                string.IsNullOrEmpty(SendAddress.Text))
            {
                MessageBox.Show("请输入正确的数据,不能为空!");
                return;
            }

            try
            {
                SetUserAndSendInfo();

                ResultText.Text = "";
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

                service.Credentials = new WebCredentials(UserName.Text, Psw.Text, DomainName.Text);

                service.TraceEnabled = true;
                service.TraceFlags = TraceFlags.All;
                service.TraceListener = this;

                service.AutodiscoverUrl(SendAddress.Text, RedirectionUrlValidationCallback);

                EmailMessage email = new EmailMessage(service);

                email.ToRecipients.Add(SendAddress.Text);

                email.Subject = "HelloWorld";
                email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");

                email.Send();
            }
            catch(Exception ex)
            {
                ResultText.Text += ex.Message;
            }
        }
示例#45
0
        public List<string> CCRecipientsSum(EmailMessage message, string[] CCRecipient)
        {
            List<string> CCRecipients = CCRecipient.OfType<string>().ToList();

            return CCRecipients;
        }
示例#46
0
        public string OutlookMain(string Subject, string BodyText, string[] ToRecipient, string[] ToRecipientC = null, string Attachment = "", bool Save = false,  bool isUseDefaultCredentials=true, string SenderEmailAddress="")
        {
            try
             {

                       EmailMessage message = new EmailMessage(GetService(isUseDefaultCredentials));

                       if (SenderEmailAddress != "")
                       {
                          message.From = SenderEmailAddress;
                       }

                        message.Subject = Subject;
                        message.Body = BodyText;

                        foreach (string  subList in ToRecipientsSum(message, ToRecipient))
                        {

                            message.ToRecipients.Add(subList);

                        }

                        if (ToRecipientC != null)
                        {
                            foreach (string subList in CCRecipientsSum(message, ToRecipientC))
                            {

                                message.CcRecipients.Add(subList);

                            }
                        }

                        if (!string.IsNullOrEmpty(Attachment))
                        {
                            message.Attachments.AddFileAttachment(Attachment);
                        }

                        if (Save == true)
                        {
                            message.Save();
                        }
                        message.SendAndSaveCopy();

                        MessageSent=MyConstans.Successful;

              }
             catch(ServiceResponseException)
                {

                    MessageSent = MyConstans.WrongMail;

                 }
               catch (ServiceRequestException)
               {

                   MessageSent = MyConstans.Authenticationfailed;

               }
             catch (Exception)
              {
                  throw;

              }

              return MessageSent;
        }
示例#47
0
        /// <summary>
        /// Forms the memory stream of the mail with attachments.
        /// </summary>
        /// <param name="collectionOfAttachments">Collection of attachments as dictionary</param>
        /// <returns>Memory stream of the created mail object</returns>
        internal MemoryStream GetMailAsStream(Dictionary<string, Stream> collectionOfAttachments, string[] documentUrls, bool attachmentFlag)
        {
            MemoryStream result = null;
            string documentUrl = string.Empty;
            try
            {
                // need to be able to update/configure or get current version of server
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or explicitly specify the admin account (set default to false)
                service.Credentials = new WebCredentials(generalSettings.AdminUserName, generalSettings.AdminPassword);
                service.Url = new Uri(generalSettings.ExchangeServiceURL);
                Microsoft.Exchange.WebServices.Data.EmailMessage email = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);
                email.Subject = documentSettings.MailCartMailSubject;

                if (attachmentFlag)
                {
                    email.Body = new MessageBody(documentSettings.MailCartMailBody);
                    foreach (KeyValuePair<string, Stream> mailAttachment in collectionOfAttachments)
                    {
                        if (null != mailAttachment.Value)
                        {
                            // Remove the date time string before adding the file as an attachment
                            email.Attachments.AddFileAttachment(mailAttachment.Key.Split('$')[0], mailAttachment.Value);
                        }
                    }
                }
                else
                {
                    int index = 0;
                    foreach (string currentURL in documentUrls)
                    {
                        if (null != currentURL && 0 < currentURL.Length)
                        {
                            string[] currentAssets = currentURL.Split('$');
                            string documentURL = generalSettings.SiteURL + currentAssets[1];
                            string documentName = currentAssets[2];

                            documentUrl = string.Concat(documentUrl, string.Format(CultureInfo.InvariantCulture, "{0} ) {1} : <a href='{2}'>{2} </a><br/>" , ++index, documentName, documentURL));
                        }
                    }
                    documentUrl = string.Format(CultureInfo.InvariantCulture, "<div style='font-family:Calibri;font-size:12pt'>{0}</div>", documentUrl);
                    email.Body = new MessageBody(documentUrl);
                }
                //// This header allows us to open the .eml in compose mode in outlook
                email.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Unsent", MapiPropertyType.String), "1");
                email.Save(WellKnownFolderName.Drafts); // must save draft in order to get MimeContent
                email.Load(new PropertySet(EmailMessageSchema.MimeContent));
                MimeContent mimcon = email.MimeContent;
                //// Do not make the StylCop fixes for MemoryStream here
                MemoryStream fileContents = new MemoryStream();
                fileContents.Write(mimcon.Content, 0, mimcon.Content.Length);
                fileContents.Position = 0;
                result = fileContents;
            }
            catch (Exception exception)
            {
                //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                MemoryStream fileContents = new MemoryStream();
                result = fileContents;
            }
            return result;
        }
 public MessageAttachment(EWS.EmailMessage email)
 {
     _message      = new EmailMessage(email);
     this.FileName = GetEmailFileName(_message);
 }
示例#49
0
        private bool SendEmail(string toEmailAddress, string htmlBody, string subject, BodyType theBodyType)
        {
            try
            {
                EmailMessage message = new EmailMessage(exchService);
                message.Subject = subject;
                message.Body = htmlBody;
                message.Body.BodyType = theBodyType;
                message.ToRecipients.Add(toEmailAddress);
                message.SendAndSaveCopy();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
示例#50
0
        /// <summary>
        /// Forms the memory stream of the mail with attachments.
        /// </summary>
        /// <param name="collectionOfAttachments">Collection of attachments as dictionary</param>
        /// <returns>Memory stream of the created mail object</returns>
        internal MemoryStream GetMailAsStream(Dictionary <string, Stream> collectionOfAttachments, string[] documentUrls, bool attachmentFlag)
        {
            MemoryStream result      = null;
            string       documentUrl = string.Empty;

            try
            {
                // need to be able to update/configure or get current version of server
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
                //// can use on premise exchange server credentials with service.UseDefaultCredentials = true, or explicitly specify the admin account (set default to false)
                service.Credentials = new WebCredentials(generalSettings.AdminUserName, generalSettings.AdminPassword);
                service.Url         = new Uri(generalSettings.ExchangeServiceURL);
                Microsoft.Exchange.WebServices.Data.EmailMessage email = new Microsoft.Exchange.WebServices.Data.EmailMessage(service);
                email.Subject = documentSettings.MailCartMailSubject;

                if (attachmentFlag)
                {
                    email.Body = new MessageBody(documentSettings.MailCartMailBody);
                    foreach (KeyValuePair <string, Stream> mailAttachment in collectionOfAttachments)
                    {
                        if (null != mailAttachment.Value)
                        {
                            // Remove the date time string before adding the file as an attachment
                            email.Attachments.AddFileAttachment(mailAttachment.Key.Split('$')[0], mailAttachment.Value);
                        }
                    }
                }
                else
                {
                    int index = 0;
                    foreach (string currentURL in documentUrls)
                    {
                        if (null != currentURL && 0 < currentURL.Length)
                        {
                            string[] currentAssets = currentURL.Split('$');
                            string   documentURL   = generalSettings.SiteURL + currentAssets[1];
                            string   documentName  = currentAssets[2];

                            documentUrl = string.Concat(documentUrl, string.Format(CultureInfo.InvariantCulture, "'{0} ) {1} : <a href='{2}'>{2} </a><br/>", ++index, documentName, documentURL));
                        }
                    }
                    documentUrl = string.Format(CultureInfo.InvariantCulture, "<div style='font-family:Calibri;font-size:12pt'>{0}</div>", documentUrl);
                    email.Body  = new MessageBody(documentUrl);
                }
                //// This header allows us to open the .eml in compose mode in outlook
                email.SetExtendedProperty(new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Unsent", MapiPropertyType.String), "1");
                email.Save(WellKnownFolderName.Drafts); // must save draft in order to get MimeContent
                email.Load(new PropertySet(EmailMessageSchema.MimeContent));
                MimeContent mimcon = email.MimeContent;
                //// Do not make the StylCop fixes for MemoryStream here
                MemoryStream fileContents = new MemoryStream();
                fileContents.Write(mimcon.Content, 0, mimcon.Content.Length);
                fileContents.Position = 0;
                result = fileContents;
            }
            catch (Exception exception)
            {
                //Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                MemoryStream fileContents = new MemoryStream();
                result = fileContents;
            }
            return(result);
        }
        private static async Task <bool> SendByExchangeAsync(EmailNetConfiguration emailConfig)
        {
            Exchange.ExchangeService service = new Exchange.ExchangeService(emailConfig.EmailExchange.ExchangeVersion);
            service.Credentials = new NetworkCredential(emailConfig.Username, emailConfig.Password);

            if (emailConfig.EmailExchange.IsTraceEnabled)
            {
                service.TraceEnabled = true;
                service.TraceFlags   = emailConfig.EmailExchange.TraceFlags;
            }

            service.AutodiscoverUrl(emailConfig.EmailAddress.FromEmail, RedirectionUrlValidationCallback);

            Exchange.EmailMessage message = new Exchange.EmailMessage(service);
            message.Subject = emailConfig.Subject;
            message.Body    = new Exchange.MessageBody(emailConfig.Body.Value);
            emailConfig.To.ForEach(to => message.ToRecipients.Add(new Exchange.EmailAddress(to.FromEmail)));

            if (emailConfig.Bcc?.Count > 0)
            {
                emailConfig.Bcc.ForEach(bcc => message.BccRecipients.Add(new Exchange.EmailAddress(bcc.FromEmail)));
            }

            if (emailConfig.Cc?.Count > 0)
            {
                emailConfig.Cc.ForEach(cc => message.CcRecipients.Add(new Exchange.EmailAddress(cc.FromEmail)));
            }

            if (emailConfig.Attachement.IsAttachement)
            {
                Utils.IsDirectoryExistsThrowException(emailConfig.Attachement.AttachementPathDirectory);

                if (emailConfig.Zip.IsCompressed)
                {
                    Utils.ZipFiles(emailConfig.Attachement.AttachementPathDirectory, emailConfig.Zip.ZipPathDirectory, emailConfig.Zip.IsDelete);

                    var file = Utils.ReadAllBytes(emailConfig.Zip.ZipPathDirectory).FirstOrDefault();

                    message.Attachments.AddFileAttachment(file.filename);

                    if (emailConfig.Zip.IsDelete)
                    {
                        Utils.DeleteFilesDirectory(emailConfig.Zip.ZipPathDirectory, true);
                    }
                }
                else
                {
                    foreach (var file in Utils.ReadAllBytes(emailConfig.Attachement.AttachementPathDirectory))
                    {
                        message.Attachments.AddFileAttachment(file.filename);
                    }
                }
            }

            Utils.Show($"\nEnviando email con {nameof(EmailNetService)}...");

            await message.Save();

            await message.SendAndSaveCopy();

            return(await Task.FromResult(true));
        }