Пример #1
0
        private void HandleAttachments(Redemption.SafeMailItemClass mailItem,
                                        AttachmentCollection attachments)
        {
            for (int i = 1; i <= mailItem.Attachments.Count; i++)
            {
                Redemption.Attachment attachmentToCopy = mailItem.Attachments.Item(i);

                object objAttach = attachmentToCopy.AsArray;
                byte[] bytes = objAttach as byte[];

                if (bytes != null)
                {
                    System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes);
                   
                    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(memStream, attachmentToCopy.FileName);

                    attachments.Add(attachment);

                    //event publishing to notify GUI we have processed another attachment.
                    if (AttachmentFound != null)
                    {
                        AttachmentFound(this, new AttachmentEventArgs(attachment));
                    }
                   
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Sends emails to the specified address.
        /// </summary>
        /// <param name="from">From name.</param>
        /// <param name="fromEmail">From email.</param>
        /// <param name="toEmails">Collection of To emails.</param>
        /// <param name="subject">Email subject</param>
        /// <param name="text">Email body.</param>
        /// <param name="attachPath">Path to the attachment.</param>
        /// <param name="isHtmlFormat">Send in html format.</param>
        /// <returns>True if succedeed.</returns>
        public bool SendEmail(String from, String fromEmail, IEnumerable<MailAddress> toEmails, String subject,
                              String text, AttachmentCollection attachPath, bool isHtmlFormat)
        {

            var message = new MailMessage();

            if (attachPath != null && attachPath.Count > 0)
            {
                foreach (Attachment att in attachPath)
                {
                    message.Attachments.Add(att);
                }
            }

            message.From = new MailAddress(fromEmail, from);
            foreach (MailAddress address in toEmails)
            {
                message.To.Add(address);
            }
            message.Subject = subject;
            message.IsBodyHtml = isHtmlFormat;
            message.Body = text;

            if (!isHtmlFormat)
            {
                message.BodyEncoding = Encoding.ASCII;
            }
            else
            {
                message.BodyEncoding = Encoding.UTF8;
            }

            return SendMail(message);
        }
Пример #3
0
        /// <summary>
        /// Initializes MailerBase using the default SmtpMailSender and system Encoding.
        /// </summary>
        /// <param name="mailSender">The underlying mail sender to use for delivering mail.</param>
        /// <param name="defaultMessageEncoding">The default encoding to use when generating a mail message.</param>
        protected MailerBase(IMailSender mailSender = null, Encoding defaultMessageEncoding = null)
        {
            From = null;
            Subject = null;
            To = new List<string>();
            CC = new List<string>();
            BCC = new List<string>();
            ReplyTo = new List<string>();
            Headers = new Dictionary<string, string>();
            Attachments = new AttachmentCollection();
            MailSender = mailSender ?? new SmtpMailSender();
            MessageEncoding = defaultMessageEncoding ?? Encoding.UTF8;

            if (System.Web.HttpContext.Current != null)
            {
                HttpContextBase = new HttpContextWrapper(System.Web.HttpContext.Current);
                var routeData = RouteTable.Routes.GetRouteData(HttpContextBase) ?? new RouteData();
                var requestContext = new RequestContext(HttpContextBase, routeData);
                base.Initialize(requestContext);
            }
            else
            {
                //Проверить!!!!!
                HttpContextBase = new HttpContextWrapper(new HttpContext(
            new HttpRequest(null, "http://tempuri.org", null),
            new HttpResponse(null)));
                var routeData = RouteTable.Routes.GetRouteData(HttpContextBase) ?? new RouteData();
                var requestContext = new RequestContext(HttpContextBase, routeData);
                base.Initialize(requestContext);

            }
        }
Пример #4
0
 public MessageChildren()
     : base()
 {
     MetaTagFXDelPropBeforeRecv = FTFactory.Instance.CreateFxDelMetaProperty();
     Recipients = FTFactory.Instance.CreateRecipientCollection();
     MetaTagFXDelPropBeforeAttach = FTFactory.Instance.CreateFxDelMetaProperty();
     Attachments = FTFactory.Instance.CreateAttachmentCollection();
     Children.Add(MetaTagFXDelPropBeforeRecv);
     Children.Add(Recipients);
     Children.Add(MetaTagFXDelPropBeforeAttach);
     Children.Add(Attachments);
 }
Пример #5
0
		public MailMessage () {
			this.to = new MailAddressCollection ();

			alternateViews = new AlternateViewCollection ();
			attachments = new AttachmentCollection ();
			bcc = new MailAddressCollection ();
			cc = new MailAddressCollection ();
			replyTo = new MailAddressCollection ();
			headers = new NameValueCollection ();

			headers.Add ("MIME-Version", "1.0");
		}
Пример #6
0
        /// <summary>
        /// Populates <paramref name="target"/> with properties copied from <paramref name="source"/>.
        /// </summary>
        /// <param name="source">The source object to copy.</param>
        /// <param name="target">The target object to populate.</param>
        private void Convert(MailAttachmentSerializableList source, AttachmentCollection target)
        {
            if (source == null)
            {
                return;
            }

            foreach (MailAttachmentSerializable item in source)
            {
                Attachment attachment = new Attachment(new MemoryStream(item.Data), item.Filename);
                target.Add(attachment);
            }
        }
Пример #7
0
        /// <summary>
        /// Hàm gửi email
        /// </summary>
        /// <param name="userName">Tài khoản</param>
        /// <param name="password">Mật khẩu</param>
        /// <param name="subject">Tiêu đề</param>
        /// <param name="body">Nội dung</param>
        /// <param name="from">Gửi từ</param>
        /// <param name="from">Tên người gửi</param>
        /// <param name="tos">Gửi đến</param>
        /// <param name="host">Server mail</param>
        /// <param name="port">Cổng</param>
        /// <param name="isSsl">Có sử dụng ssl hay không</param>
        /// <param name="isUseDefauletCredentials">Sử dụng tài khoản mặc định hay k</param>
        /// <param name="bcc">Danh sách email bcc</param>
        /// <param name="cc">Danh sách email cc</param>
        /// <param name="attachCollection">Đính kèm theo</param>
        public static bool SendEmail(string userName, string password, string subject, string body, string from, string fromName, List<string> tos, string host, int port, bool isSsl, bool isUseDefauletCredentials = false, List<string> bcc = null, List<string> cc = null, AttachmentCollection attachCollection = null)
        {
            try
            {
                if (string.IsNullOrEmpty(body) || string.IsNullOrEmpty(from) || tos == null || tos.Count <= 0 || port <= 0 || string.IsNullOrEmpty(host))
                    return false;
                if (!isUseDefauletCredentials)
                    if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                        return false;

                var message = new MailMessage();
                message.From = new MailAddress(from, fromName);
                foreach (var address in tos.Where(to => !String.IsNullOrWhiteSpace(to)))
                    message.To.Add(address.Trim());

                if (null != bcc)
                    foreach (var address in bcc.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                        message.Bcc.Add(address.Trim());

                if (null != cc)
                    foreach (var address in cc.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                        message.CC.Add(address.Trim());

                if (attachCollection != null && attachCollection.Count > 0)
                    foreach (Attachment attach in attachCollection)
                        message.Attachments.Add(attach);

                message.Subject = subject;
                message.Body = body;
                message.IsBodyHtml = true;

                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Host = host;
                    smtpClient.Port = port;
                    smtpClient.EnableSsl = isSsl;
                    if (isUseDefauletCredentials)
                        smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                    else
                        smtpClient.Credentials = new NetworkCredential(userName, password);
                    smtpClient.Send(message);
                }
                return true;
            }
            catch (Exception ex)
            {
                FileExceptionHandler.Handle(ex, "MailUtility", "SendEmail");
                throw ex;
            }
        }
Пример #8
0
 /// <summary>
 /// Initializes MailerBase using the default SmtpMailSender and system Encoding.
 /// </summary>
 /// <param name="mailSender">The underlying mail sender to use for delivering mail.</param>
 /// <param name="defaultMessageEncoding">The default encoding to use when generating a mail message.</param>
 protected MailerBase(IMailSender mailSender = null, Encoding defaultMessageEncoding = null)
 {
     From = null;
     Subject = null;
     To = new List<string>();
     CC = new List<string>();
     BCC = new List<string>();
     ReplyTo = new List<string>();
     Headers = new Dictionary<string, string>();
     Attachments = new AttachmentCollection();
     MailSender = mailSender ?? new SmtpMailSender();
     MessageEncoding = defaultMessageEncoding ?? Encoding.UTF8;
     if (System.Web.HttpContext.Current != null)
         HttpContextBase = new HttpContextWrapper(System.Web.HttpContext.Current);
 }
Пример #9
0
 /// <summary>
 /// Sends emails to the specified address.
 /// </summary>
 /// <param name="from">From name.</param>
 /// <param name="fromEmail">From email.</param>
 /// <param name="to">To name.</param>
 /// <param name="toEmail">To email.</param>
 /// <param name="subject">Email subject</param>
 /// <param name="text">Email body.</param>
 /// <param name="attachPath">Path to the Attachments.</param>
 /// <param name="isHtmlFormat">Send in html format.</param>
 /// <returns>True if succedeed.</returns>
 public bool SendEmail(String from, String fromEmail, String to, String toEmail, String subject, String text,
                       AttachmentCollection attachPath, bool isHtmlFormat)
 {
     try
     {
         var recipients = new MailAddressCollection
                              {
                                  new MailAddress(toEmail, to)
                              };
         return SendEmail(from, fromEmail, recipients, subject, text, attachPath, isHtmlFormat);
     }
     catch (Exception ex)
     {
         return false;
     }
 }
Пример #10
0
        /// <summary>
        /// Send email with Attachments, can be set to NULL, in case of no attachments.
        /// </summary>
        /// <param name="from">User Name</param>
        /// <param name="toList">Comma separated To list</param>
        /// <param name="subject">Email Subject</param>
        /// <param name="body">Email body</param>
        /// <param name="isBodyHtml">Specify if you want to HTML content</param>
        /// <param name="attachmentCollection">Attachments</param>
        public void SendMail(string from, string toUserList, string subject, string body, bool isBodyHtml, AttachmentCollection attachmentCollection)
        {
            try
            {
                // Create mail message
                MailMessage message = new MailMessage();
                // Get the default from address if the from address is null
                message.From = new MailAddress(from);

                if (toUserList != null && toUserList != string.Empty)
                {
                    // Add recipients to from to list
                    foreach (string to in toUserList.Split(','))
                    {
                        message.To.Add(to);
                    }
                }
                else
                {
                    throw new Exception("Calls must specify TO user email id.");
                }

                message.Body = body;
                message.Subject = subject;
                message.IsBodyHtml = isBodyHtml;

                if (attachmentCollection != null)
                {
                    foreach (Attachment fileAttachment in attachmentCollection)
                    {
                        message.Attachments.Add(fileAttachment);
                    }
                }

                // Create smpt client instance
                SmtpClient mailClient = new SmtpClient(this.hostName, this.portNumber);
                mailClient.EnableSsl = this.enableSSL;
                mailClient.Send(message);

                System.Diagnostics.Debug.Write("Email sent to " + toUserList.ToString(), category);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.Write("Exception:" + exception.Message + exception.StackTrace, category);
            }
        }
Пример #11
0
		/// <summary>
		/// Send the email.
		/// </summary>
		/// <param name="EmailFrom"></param>
		/// <param name="EmailTo"></param>
		/// <param name="Subject"></param>
		/// <param name="Body"></param>
		/// <param name="Attachments"></param>
		/// <param name="CC"></param>
		/// <param name="BCC"></param>
		/// <param name="SMTPServer"></param>
		/// <param name="Mailformat"></param>
		/// <returns></returns>
        public bool SendMail(MailAddress EmailFrom, MailAddressCollection EmailTo, string Subject, string Body, AttachmentCollection AttachmentFiles, MailAddressCollection CC, MailAddressCollection BCC, SmtpClient SMTPServer, bool IsBodyHtml)
		{
			try
			{
				MailMessage Newmail = new MailMessage();
                Newmail.IsBodyHtml = IsBodyHtml;
                Newmail.Subject = Subject;
                Newmail.Body = Body;
                Newmail.From = EmailFrom;
                Newmail.Sender = EmailFrom;
                foreach (MailAddress recepient in EmailTo)
                    Newmail.To.Add(recepient);

                foreach (MailAddress ccrecepient in CC)
                    Newmail.CC.Add(ccrecepient);

                foreach (MailAddress bccrecepient in BCC)
                    Newmail.CC.Add(bccrecepient);

                foreach (Attachment attachment in AttachmentFiles)
                    Newmail.Attachments.Add(attachment);

				if (SMTPServer.Host != string.Empty)
				{
					SMTPServer.Host = "localhost";
				}

                SMTPServer.Send(Newmail);
				
				return true;
			}
			catch(Exception ex)
			{
				throw ex;
			}
		}
Пример #12
0
        //Чтение почты
        public static void ReadNewEmail()
        {
            attachments_string = null; //Обнуляем

            string from        = null;
            string subject     = null;
            string messageText = null;
            string message2vk  = null;

            System.Net.Mail.Attachment           att      = null;
            System.Net.Mail.AttachmentCollection att_coll = null;
            //Получение нового письма, его текста и темы, от кого (ИМЯ)
            string hostname = SMTP_SERVER,
                   username = FROM_EMAIL, password = FROM_PWD;

            // The default port for IMAP over SSL is 993.
            using (ImapClient client = new ImapClient(hostname, 993, username, password, AuthMethod.Login, true))
            {
                Console.WriteLine("Связь с email-сервером установлена! Проверка почты...");


                // Returns a collection of identifiers of all mails matching the specified search criteria.
                IEnumerable <uint> uids = client.Search(SearchCondition.Unseen());

                // Download mail messages from the default mailbox.
                //ФОрмирование списка вложение из почты если они меньше 2MB
                // The expression will be evaluated for every MIME part of every mail message
                // in the uids collection.
                IEnumerable <MailMessage> messages = client.GetMessages(uids,
                                                                        (Bodypart part) =>
                {
                    // We're only interested in attachments.
                    if (part.Disposition.Type == ContentDispositionType.Attachment)
                    {
                        Int64 TwoMegabytes = (1024 * 1024 * 2);
                        if (part.Size > TwoMegabytes)
                        {
                            // Don't download this attachment.
                            return(false);
                        }
                    }

                    // Fetch MIME part and include it in the returned MailMessage instance.
                    return(true);
                }
                                                                        );

                foreach (var mess in messages)
                {
                    //Кодировка
                    mess.BodyEncoding    = System.Text.Encoding.UTF8;
                    mess.SubjectEncoding = System.Text.Encoding.UTF8;
                    mess.HeadersEncoding = System.Text.Encoding.UTF8;

                    from    = mess.From.DisplayName;
                    subject = mess.Subject;
                    //var encoding = mess.HeadersEncoding;
                    messageText = mess.Body;

                    Console.WriteLine(from + "\n" + subject + "\n" + messageText);

                    message2vk = "От: " + from + "\n" + "Тема: " + subject + "\n" + "Сообщение: " + messageText;
                    if (mess.Attachments != null)
                    {
                        message2vk += "\n-------------------------\n Вложения смотрите на почте [email protected]";
                    }
                }

                // Put calling thread to sleep. This is just so the example program does
                // not immediately exit.
                Thread.Sleep(100);
            }

            // Скачивание и сохранение с почты вложений

            // Отправка ВК
            if (messageText != null)
            {
                PosterOnWall(attachments_string, message2vk, group_id);
            }
            //return message2vk;
        }
Пример #13
0
        /// <summary>
        /// Convert CID: object references to Base-64 encoded versions.
        /// </summary>
        /// <remarks>Useful for displaying text/html messages with image references.</remarks>
        /// <param name="html">HTML block to process.</param>
        /// <param name="attachments">Collection of attachments available to be embedded.</param>
        /// <returns>The HTML block with any CID: object references replaced by their Base-64 encoded bytes.</returns>
        public static string EmbedAttachments(string html, AttachmentCollection attachments)
        {
            // Build a new string using the following buffer.
            StringBuilder htmlBuilder = new StringBuilder(Constants.MEDIUMSBSIZE);

            int srcStartPos = 0, lastPos = 0;
            while (srcStartPos > -1)
            {
                // Find the next SRC= attribute and handle either single or double quotes.
                int srcStartQuotePos = html.IndexOf("src=\"cid:", srcStartPos, StringComparison.Ordinal);
                int srcStartApostrophePos = html.IndexOf("src='cid:", srcStartPos, StringComparison.Ordinal);

                if (srcStartQuotePos > -1)
                {
                    if (srcStartApostrophePos > -1)
                        srcStartPos = srcStartQuotePos < srcStartApostrophePos ? srcStartQuotePos : srcStartApostrophePos;
                    else
                        srcStartPos = srcStartQuotePos;
                }
                else if (srcStartApostrophePos > -1)
                    srcStartPos = srcStartApostrophePos;
                else
                    srcStartPos = -1;

                string srcEndDelimiter = (srcStartQuotePos == srcStartPos) ? "\"" : "'";

                if (srcStartPos > -1)
                {
                    int srcEndPos = html.IndexOf(srcEndDelimiter, srcStartPos + 9, StringComparison.Ordinal);
                    if (srcEndPos > 0)
                    {
                        htmlBuilder.Append(html.Substring(lastPos, srcStartPos + 5 - lastPos));

                        string cid = html.Substring(srcStartPos + 9, srcEndPos - srcStartPos - 9);

                        // Check for attachments with matching Content-IDs.
                        bool matchingAttachmentFound = false;
                        foreach (Attachment attachment in attachments)
                        {
                            if (attachment.ContentId == cid)
                            {
                                htmlBuilder.Append("data:" + attachment.ContentType.MediaType + ";base64,");

                                matchingAttachmentFound = true;
                                byte[] contentStreamBytes = ((MemoryStream)attachment.ContentStream).ToArray();

                                htmlBuilder.Append(ToBase64String(contentStreamBytes, 0, contentStreamBytes.Length));
                            }
                        }

                        // If the current object hasn't been matched, look for a matching file name.
                        if (!matchingAttachmentFound)
                        {
                            // Ignore the non-file name portion of this Content-ID.
                            int cidAtPos = cid.IndexOf("@", StringComparison.Ordinal);
                            if (cidAtPos > -1)
                                cid = cid.Substring(0, cidAtPos);

                            foreach (Attachment attachment in attachments)
                            {
                                if (attachment.Name == cid)
                                {
                                    htmlBuilder.Append("data:" + attachment.ContentType.MediaType + ";base64,");

                                    matchingAttachmentFound = true;
                                    byte[] contentStreamBytes = ((MemoryStream)attachment.ContentStream).ToArray();

                                    htmlBuilder.Append(ToBase64String(contentStreamBytes, 0, contentStreamBytes.Length));
                                }
                            }

                            if (!matchingAttachmentFound)
                                htmlBuilder.Append(cid);
                        }

                        srcStartPos = srcEndPos;
                        lastPos = srcStartPos;
                    }
                    else
                        srcStartPos = -1;
                }
                else
                    srcStartPos = -1;
            }

            htmlBuilder.Append(html.Substring(lastPos));

            return htmlBuilder.ToString();
        }
Пример #14
0
		public void GetReady ()
		{
			ac = new MailMessage ("*****@*****.**", "*****@*****.**").Attachments;
			a = Attachment.CreateAttachmentFromString ("test", new ContentType ("text/plain"));
		}
Пример #15
0
 private void CopyToAttachmentCollection(Rebex.Mail.AttachmentCollection rac, AttachmentCollection ac)
 {
     foreach (Rebex.Mail.Attachment ra in rac)
     {
         ac.Add(ToAttachment(ra));
     }
 }
Пример #16
0
 public static async Task <string> SendEmail(string mailTos, string mailCcs, string subject, string content, System.Net.Mail.AttachmentCollection attach)
 {
     try
     {
         System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
         string html = "";
         html  = content + "<br/>";
         html += "<p><strong>Tr&acirc;n trọng,</strong><br />";
         html += "ERP24H System<br />";
         html += "Email: [email protected]<br />";
         html += "Phone: 0986 858 724</p>";
         // mail.To.Add("*****@*****.**");
         var listmails = mailTos.Split(';').ToList();
         if (listmails.Count() > 0)
         {
             foreach (var item in listmails)
             {
                 if (IsValidEmail(item))
                 {
                     mail.To.Add(item);
                 }
             }
         }
         mail.Subject    = subject;
         mail.From       = new MailAddress("*****@*****.**");
         mail.Body       = HttpUtility.HtmlDecode(html);
         mail.IsBodyHtml = true;
         System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
         if (attach.Count > 0)
         {
             foreach (var a in attach)
             {
                 mail.Attachments.Add(a);
             }
         }
         smtp.Port                  = 587;
         smtp.Host                  = "smtp.gmail.com";
         smtp.EnableSsl             = true;
         smtp.UseDefaultCredentials = false;
         smtp.DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network;
         smtp.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "crm@2016");
         smtp.Send(mail);
         return("");
     }
     catch (Exception ex)
     {
         return("");
     }
 }
 public MailBuilder AttachFiles(AttachmentCollection attachments)
 {
     return this.AttachFiles(attachments.ToList());
 }