/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpSignature"/> /// class with a Content-Type of application/pgp-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPgpSignature(Stream stream) : base("application", "pgp-signature") { ContentObject = new ContentObject (stream, ContentEncoding.Default); ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.SevenBit; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Signature"/> /// class with a Content-Type of application/pkcs7-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pkcs7-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Signature (Stream stream) : base ("application", "pkcs7-signature") { ContentDisposition = new ContentDisposition (ContentDisposition.Attachment); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject (stream); FileName = "smime.p7s"; }
public static void Filename_Roundtrip() { var cd = new ContentDisposition(); Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = "hello"; Assert.Equal("hello", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("hello", cd.Parameters["filename"]); Assert.Equal("attachment; filename=hello", cd.ToString()); cd.FileName = "world"; Assert.Equal("world", cd.FileName); Assert.Equal(1, cd.Parameters.Count); Assert.Equal("world", cd.Parameters["filename"]); Assert.Equal("attachment; filename=world", cd.ToString()); cd.FileName = null; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); cd.FileName = string.Empty; Assert.Null(cd.FileName); Assert.Empty(cd.Parameters); }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> class. /// </summary> /// <remarks> /// <para>Creates a new MIME part with a Content-Type of application/pkcs7-mime /// and the <paramref name="stream"/> as its content.</para> /// <para>Unless you are writing your own pkcs7 implementation, you'll probably /// want to use the <see cref="Compress(MimeEntity)"/>, /// <see cref="Encrypt(CmsRecipientCollection, MimeEntity)"/>, and/or /// <see cref="Sign(CmsSigner, MimeEntity)"/> method to create new instances /// of this class.</para> /// </remarks> /// <param name="type">The S/MIME type.</param> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="type"/> is not a valid value. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPkcs7Mime (SecureMimeType type, Stream stream) : base ("application", "pkcs7-mime") { ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.Base64; ContentObject = new ContentObject (stream); switch (type) { case SecureMimeType.CompressedData: ContentType.Parameters["smime-type"] = "compressed-data"; ContentDisposition.FileName = "smime.p7z"; ContentType.Name = "smime.p7z"; break; case SecureMimeType.EnvelopedData: ContentType.Parameters["smime-type"] = "enveloped-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.SignedData: ContentType.Parameters["smime-type"] = "signed-data"; ContentDisposition.FileName = "smime.p7m"; ContentType.Name = "smime.p7m"; break; case SecureMimeType.CertsOnly: ContentType.Parameters["smime-type"] = "certs-only"; ContentDisposition.FileName = "smime.p7c"; ContentType.Name = "smime.p7c"; break; default: throw new ArgumentOutOfRangeException ("type"); } }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpSignature"/> /// class with a Content-Type of application/pgp-signature. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-signature /// and the <paramref name="stream"/> as its content. /// </remarks> /// <param name="stream">The content stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ApplicationPgpSignature (Stream stream) : base ("application", "pgp-signature") { ContentDisposition = new ContentDisposition (ContentDisposition.Attachment); ContentTransferEncoding = ContentEncoding.SevenBit; ContentObject = new ContentObject (stream); FileName = "signature.pgp"; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.ApplicationPgpEncrypted"/> class. /// </summary> /// <remarks> /// Creates a new MIME part with a Content-Type of application/pgp-encrypted /// and content matching <c>"Version: 1\n"</c>. /// </remarks> public ApplicationPgpEncrypted () : base ("application", "pgp-encrypted") { ContentDisposition = new ContentDisposition ("attachment"); ContentTransferEncoding = ContentEncoding.SevenBit; var content = new MemoryStream (Encoding.UTF8.GetBytes ("Version: 1\n"), false); ContentObject = new ContentObject (content); }
public void ConstructorWithOtherPropertyValues_ShouldSetAppropriately() { var cd = new ContentDisposition("attachment;creation-date=\"" + ValidDateTimeLocal + "\";read-date=\"" + ValidDateTimeLocal + "\";modification-date=\"" + ValidDateTimeLocal + "\";filename=\"=?utf-8?B?dGVzdC50eHTnkIY=?=\";size=200"); Assert.Equal("attachment", cd.DispositionType); Assert.False(cd.Inline); Assert.Equal(200, cd.Size); Assert.Equal("=?utf-8?B?dGVzdC50eHTnkIY=?=", cd.FileName); cd.FileName = "test.txt\x7406"; Assert.Equal("test.txt\x7406", cd.FileName); }
public static void DefaultCtor_ExpectedDefaultPropertyValues() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal("attachment", cd.DispositionType); Assert.Null(cd.FileName); Assert.False(cd.Inline); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Empty(cd.Parameters); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Equal(-1, cd.Size); Assert.Equal("attachment", cd.ToString()); }
/// <summary> /// Downloads the file to disk, storing the path into the DownloadedFile field. /// </summary> public void Download(ProgressChangedEventHandler handler) { if (DownloadedFile != null && DownloadedFile.Length > 0) { throw new InvalidOperationException("The Download method cannot be called " + "before the Download method has been called."); } //Create a folder to hold all our updates. lock (TempPathLock) { if (TempPath == null) { TempPath = new DirectoryInfo(Path.GetTempPath()); TempPath = TempPath.CreateSubdirectory("eraser" + Environment.TickCount.ToString( CultureInfo.InvariantCulture)); } } //Create the progress manager for this download. ProgressManager progress = new ProgressManager(); try { Uri downloadLink = Link; ContentDisposition contentDisposition = null; for (int redirects = 0; redirects < 20; ++redirects) { //Request the download. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downloadLink); request.AllowAutoRedirect = false; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { //Check for a suggested filename. Store this until we get the final URI. foreach (string header in response.Headers.AllKeys) { if (header.ToUpperInvariant() == "CONTENT-DISPOSITION") { contentDisposition = new ContentDisposition(response.Headers[header]); } } //Handle 3xx series response codes. if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399) { //Redirect. bool locationHeader = false; foreach (string header in response.Headers.AllKeys) { if (header.ToUpperInvariant() == "LOCATION") { locationHeader = true; downloadLink = new Uri(response.Headers[header]); break; } } if (!locationHeader) { throw new WebException("A redirect response was received but no redirection" + "URI was provided."); } continue; } //Do the progress calculations progress.Total = response.ContentLength; //Create the file name. DownloadedFile = new FileInfo(Path.Combine( TempPath.FullName, string.Format(CultureInfo.InvariantCulture, "{0:00}-{1}", ++DownloadFileIndex, contentDisposition == null ? Path.GetFileName(downloadLink.GetComponents(UriComponents.Path, UriFormat.Unescaped)) : contentDisposition.FileName))); using (Stream responseStream = response.GetResponseStream()) using (FileStream fileStream = DownloadedFile.OpenWrite()) { //Copy the information into the file stream int lastRead = 0; byte[] buffer = new byte[16384]; while ((lastRead = responseStream.Read(buffer, 0, buffer.Length)) != 0) { fileStream.Write(buffer, 0, lastRead); //Compute progress progress.Completed = fileStream.Position; //Call the progress handler if (handler != null) { handler(this, new ProgressChangedEventArgs(progress, null)); } } } //Let the event handler know the download is complete. progress.MarkComplete(); if (handler != null) { handler(this, new ProgressChangedEventArgs(progress, null)); } return; } throw new WebException("The server is not redirecting properly."); } } catch (Exception e) { if (handler != null) { handler(this, new ProgressChangedEventArgs(progress, e)); } } }
private void SendMessages(SmtpClient client, SystemEmailMessage item = null, SystemEmailMessage_OTP otpItem = null, SystemEmailMessage_PDO pdoItem = null, SystemEmailMessage_NOZ nozItem = null) { bool isOTPitem = false; bool isPDOitem = false; bool isNOZItem = false; try { if (otpItem != null) { isOTPitem = true; } else if (pdoItem != null) { isPDOitem = true; } else if (nozItem != null) { isNOZItem = true; } //if (String.IsNullOrEmpty(isOTPitem ? otpItem.EmailTo : (isPDOitem ? ((pdoItem.TOEmails != null && pdoItem.TOEmails.Length > 0) ? pdoItem.TOEmails : pdoItem.EmailTo) : (isNOZItem ? nozItem.EmailTo : item.EmailTo)))) if (String.IsNullOrEmpty(isOTPitem ? otpItem.EmailTo : (isPDOitem ? pdoItem.EmailTo : (isNOZItem ? nozItem.EmailTo : item.EmailTo)))) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isNOZItem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Processed; } DataTypesHelper.LogThis("Couldn't send email! Email to is empty"); } else { string sender = "", emailTitle = "", emailTo = "", emailSubject = "", emailBody = ""; if (isOTPitem) { DataTypesHelper.LogThis("OTP ITEM!"); sender = ConfigurationManager.AppSettings["SenderOTP"].ToString(); //sender = otpItem.EmailFrom; emailTitle = "(" + otpItem.EmailFrom + ") - " + ConfigurationManager.AppSettings["EmailTitleOTP"].ToString(); emailTo = otpItem.EmailTo; emailSubject = otpItem.EmailSubject; emailBody = otpItem.EmailBody; } else if (isPDOitem) { DataTypesHelper.LogThis("PDO ITEM"); if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseUserEmailSettings"])) { if (pdoItem.OsebaEmailFromID.HasValue) { SettingsModel set = pdoSettingsRepo.GetLatestSettings(); string host = String.IsNullOrEmpty(set.EmailStreznik) ? pdoItem.Osebe_PDO.EmailStreznik : set.EmailStreznik; //int port = 587;//set.EmailVrata > 0 ? set.EmailVrata : pdoItem.Osebe_PDO.EmailVrata.Value; int port = set.EmailVrata > 0 ? set.EmailVrata : pdoItem.Osebe_PDO.EmailVrata.Value; //bool sslEnable = false;//!set.EmailSifriranjeSSL ? pdoItem.Osebe_PDO.EmailSifriranjeSSL.Value : set.EmailSifriranjeSSL; bool sslEnable = set.EmailSifriranjeSSL ? pdoItem.Osebe_PDO.EmailSifriranjeSSL.Value : set.EmailSifriranjeSSL; //var credentials = new NetworkCredential("*****@*****.**"/*pdoItem.Osebe_PDO.Email, "Geslo123."/*pdoItem.Osebe_PDO.EmailGeslo); var credentials = new NetworkCredential(pdoItem.Osebe_PDO.Email, pdoItem.Osebe_PDO.EmailGeslo); client = new SmtpClient { Host = host, Port = port, EnableSsl = sslEnable, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = credentials }; } } string emailTitleOseba = pdoItem.Osebe_PDO != null ? pdoItem.Osebe_PDO.Ime + " " + pdoItem.Osebe_PDO.Priimek : ConfigurationManager.AppSettings["EmailTitlePDO"].ToString();; sender = pdoItem.OsebaEmailFromID != null ? pdoItem.Osebe_PDO.Email : ConfigurationManager.AppSettings["SenderPDO"].ToString(); emailTitle = emailTitleOseba; emailTo = pdoItem.EmailTo; emailSubject = pdoItem.EmailSubject; emailBody = pdoItem.EmailBody; } else if (isNOZItem) { sender = ConfigurationManager.AppSettings["SenderNOZ"].ToString(); //sender = otpItem.EmailFrom; //string emailTitleOseba = nozItem.Osebe_PDO != null ? pdoItem.Osebe_PDO.Ime + " " + pdoItem.Osebe_PDO.Priimek : ConfigurationManager.AppSettings["EmailTitlePDO"].ToString(); ; //sender = nozItem.OsebaEmailFromID != null ? nozItem.Osebe_PDO.Email : ConfigurationManager.AppSettings["SenderNOZ"].ToString(); emailTitle = "(" + nozItem.EmailFrom + ") - " + ConfigurationManager.AppSettings["EmailTitleNOZ"].ToString(); emailTo = nozItem.EmailTo; emailSubject = nozItem.EmailSubject; emailBody = nozItem.EmailBody; } else { sender = ConfigurationManager.AppSettings["Sender"].ToString(); emailTitle = ConfigurationManager.AppSettings["EmailTitle"].ToString(); emailTo = item.EmailTo; emailSubject = item.EmailSubject; emailBody = item.EmailBody; } MailMessage message = new MailMessage(); // preverimo če je emailTO prazen pomeni, da vazame list pošiljateljev if (emailTo.Length > 0) { if (emailTo != null && emailTo.Length > 0) { string[] splitTOEmails = emailTo.Split(';'); if (splitTOEmails.Length > 1) { foreach (var email in splitTOEmails) { MailAddress ToEmail = new MailAddress(email); message.To.Add(ToEmail); } } else { message.To.Add(emailTo); } } } message.Sender = new MailAddress(sender); message.From = new MailAddress(sender, emailTitle); message.Subject = emailSubject; message.IsBodyHtml = true; message.Body = emailBody; message.BodyEncoding = Encoding.UTF8; if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.Processed; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Processed; } // Boris 20.11.2019: attachments string attachmentFilename = ""; if (isOTPitem || isPDOitem || isNOZItem) { attachmentFilename = isOTPitem ? otpItem.Attachments : (isPDOitem ? pdoItem.Attachments : nozItem.Attachments); } else { } // Boris 27.04.2020: CC seznam emailov if (isPDOitem) { if (pdoItem.CCEmails != null && pdoItem.CCEmails.Length > 0) { string[] splitCCEmails = pdoItem.CCEmails.Split(';'); foreach (var email in splitCCEmails) { MailAddress copy = new MailAddress(email); message.CC.Add(copy); } } } if (!string.IsNullOrEmpty(attachmentFilename)) { string[] splitAttachments = attachmentFilename.Split(';'); foreach (var fileAttachment in splitAttachments) { if (File.Exists(attachmentFilename)) { Attachment attachment = new Attachment(fileAttachment, MediaTypeNames.Application.Octet); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = File.GetCreationTime(fileAttachment); disposition.ModificationDate = File.GetLastWriteTime(fileAttachment); disposition.ReadDate = File.GetLastAccessTime(fileAttachment); disposition.FileName = Path.GetFileName(fileAttachment); disposition.Size = new FileInfo(fileAttachment).Length; disposition.DispositionType = DispositionTypeNames.Attachment; message.Attachments.Add(attachment); } } } // ------------------------------------------------------------------------------------ client.Send(message); } if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } catch (SmtpFailedRecipientsException ex) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("Couldn't send the email to receipient: " + item.EmailTo + "\n" + ex.Message); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } catch (SmtpException ex) { if (ex.Message.Contains("Mailbox unavailable")) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("Could not send the email to receipient: " + item.EmailTo); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } else { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } DataTypesHelper.LogThis("SmtpException: " + ex.Message); if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } } } catch (Exception ex) { if (isOTPitem) { otpItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isPDOitem) { pdoItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else if (isNOZItem) { nozItem.Status = (int)Enums.SystemEmailMessageStatus.RecipientError; } else { item.Status = (int)Enums.SystemEmailMessageStatus.Error; } if (isOTPitem) { otpSystemEmailMessageRepo.SaveEmail(otpItem); } else if (isPDOitem) { pdoSystemEmailMessageRepo.SaveEmail(pdoItem); } else if (isNOZItem) { nozSystemEmailMessageRepo.SaveEmail(nozItem); } else { systemEmailMessageRepo.SaveEmail(item); } DataTypesHelper.LogThis("LOG1: " + ex.Message); } }
/// <summary> /// Downloads a single file synchronously /// </summary> /// <param name="url">The URL to download the file from (either a fully qualified URL or an app relative/absolute path)</param> /// <param name="sendAuthCookie">Specifies whether the FormsAuthenticationCookie should be sent</param> /// <param name="timeout">Timeout in milliseconds</param> /// <param name="isLocal">Specifiers whether the file is located on the local server</param> public FileDownloadResponse DownloadFile(string url, bool sendAuthCookie = false, int?timeout = null, bool isLocal = false) { Guard.NotEmpty(url, nameof(url)); url = WebHelper.GetAbsoluteUrl(url, _httpRequest); HttpWebRequest req; if (isLocal) { req = WebHelper.CreateHttpRequestForSafeLocalCall(new Uri(url)); } else { req = WebRequest.CreateHttp(url); req.UserAgent = "Smartstore"; } if (timeout.HasValue) { req.Timeout = timeout.Value; } if (sendAuthCookie) { req.SetFormsAuthenticationCookie(_httpRequest); req.SetAnonymousIdentCookie(_httpRequest); req.SetVisitorCookie(_httpRequest); } using (var resp = (HttpWebResponse)req.GetResponse()) using (var stream = resp.GetResponseStream()) { if (resp.StatusCode == HttpStatusCode.OK) { var data = stream.ToByteArray(); if (data != null && data.Length != 0) { string fileName = null; var contentDisposition = resp.Headers["Content-Disposition"]; if (contentDisposition.HasValue()) { var cd = new ContentDisposition(contentDisposition); fileName = cd.FileName; } if (fileName.IsEmpty()) { try { var uri = new Uri(url); fileName = Path.GetFileName(uri.LocalPath); } catch { } } return(new FileDownloadResponse(data, fileName, resp.ContentType)); } } } return(null); }
public object UploadFileToCommon(Stream file, ContentType contentType, ContentDisposition contentDisposition, IEnumerable <System.Web.HttpPostedFileBase> files) { return(UploadFile(Global.FolderCommon.ToString(), file, contentType, contentDisposition, files, false, true)); }
private void process_NewFrame(object stateInfo) { Thread.CurrentThread.Priority = ThreadPriority.Lowest; VsData lastData = null; try { // get new one if (dataBuffer.Count > 0) { lastData = (VsData)dataBuffer.Dequeue(); } if (lastData != null) { // save image DateTime dNow = DateTime.Now; string filename = String.Format("{0}_{1}_{2}_{3}_{4}_{5}.jpg", dNow.Year.ToString(), dNow.Month.ToString(), dNow.Day.ToString(), dNow.Hour.ToString(), dNow.Minute.ToString(), dNow.Second.ToString()); lastData.Image.Save(filename, ImageFormat.Jpeg); // send image SmtpClient mySmtpClient = null; MailMessage myMail = null; try { mySmtpClient = new SmtpClient(smtpHost); // set smtp-client with basicAuthentication mySmtpClient.UseDefaultCredentials = false; System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(smtpUser, smtpPasswd); mySmtpClient.Credentials = basicAuthenticationInfo; // add from,to mailaddresses MailAddress from = new MailAddress(emailFrom, "Personal Security Alert"); MailAddress to = new MailAddress(emailTo, "Yourself"); myMail = new System.Net.Mail.MailMessage(from, to); // add ReplyTo MailAddress replyto = new MailAddress(emailFrom); myMail.ReplyTo = replyto; // set subject and encoding myMail.Subject = "Test message"; myMail.SubjectEncoding = System.Text.Encoding.UTF8; // set body-message and encoding myMail.Subject = "àµ×͹! à˵ؼԴ»¡µÔ ¨Ò¡ Personal Security System"; myMail.Body = "<b> à˵ؼԴ»¡µÔ !!! </b><br> <b> </b> <br> <b> àÇÅÒ " + DateTime.Now.ToString() + " ´ÙàÍ¡ÊÒÃṺ </b>."; myMail.BodyEncoding = System.Text.Encoding.UTF8; // text or html // set file attachment for this e-mail message. Attachment data = new Attachment(filename, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(filename); disposition.ModificationDate = System.IO.File.GetLastWriteTime(filename); disposition.ReadDate = System.IO.File.GetLastAccessTime(filename); // Add the file attachment to this e-mail message. myMail.Attachments.Add(data); myMail.IsBodyHtml = true; mySmtpClient.Send(myMail); } catch (SmtpException err) { logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace); } finally { if (mySmtpClient != null) { mySmtpClient = null; } } } } catch (Exception err) { logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);; } }
public virtual void ParseUnencoded(IMessageReader reader, ContentType contentType, ContentDisposition contentDisposition, string boundary) { byte[] buffer; bool flag = false; byte[] data = new byte[] { 13, 10 }; Label_0019: buffer = reader.ReadLine(); if (!reader.EndOfMessage) { switch (BoundaryChecker.CheckBoundary(buffer, boundary)) { case EBoundaryType.NotBoundary: if (flag) { this.ContentWriter.Write(data); } this.ContentWriter.Write(buffer); flag = true; goto Label_0019; case EBoundaryType.Final: this.RaiseFinalBoundaryReached(); break; } } }
public void GetViaDateTimeProperty_WithNonLocalTimeZone_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeNotLocal; DateTime result = cd.CreationDate; Assert.Equal(ValidDateTimeNotLocal, cd.Parameters["creation-date"]); Assert.Equal(DateTimeKind.Local, result.Kind); // be sure that the local offset isn't the same as the offset we're testing // so that this comparison will be valid if (s_localTimeOffset != new TimeSpan(-2, 0, 0)) { Assert.NotEqual(ValidDateTimeNotLocal, result.ToString("ddd, dd MMM yyyy H:mm:ss")); } }
public void GetViaDateTimeProperty_WithOtherTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); }
public void GetViaDateTimeProperty_WithLocalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(cd.Parameters["creation-date"], ValidDateTimeLocal); }
public static void GetViaDateTimeProperty_WithUniversalTime_ShouldSetDateTimeKindAppropriately() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateGmt; Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); }
public static void SetDateViaProperty_ShouldPersistToProprtyAndParametersCollection_AndRespectKindProperty() { DateTime date = new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Unspecified); var cd = new ContentDisposition("inline"); cd.CreationDate = date; Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); }
public void SetDateViaConstructor_ShouldPersistToPropertyAndPersistToParametersCollection() { string disposition = "inline; creation-date=\"" + ValidDateGmt + "\";"; string dispositionValue = "inline; creation-date=\"" + ValidDateGmtOffset + "\""; var cd = new ContentDisposition(disposition); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); Assert.Equal("inline", cd.DispositionType); Assert.Equal(dispositionValue, cd.ToString()); }
public void Evaluate(int SpreadMax) { if (FPinInDoSend.IsChanged) { for (int i = 0; i < SpreadMax; i++) { if (FPinInDoSend[i]) { string Username = FPinInUsername[i]; string Pwd = FPinInPassword[i]; if (Username == null) { Username = ""; } if (Pwd == null) { Pwd = ""; } SmtpClient EmailClient = new SmtpClient(FPinInHost[i], FPinInPort[i]); EmailClient.EnableSsl = FPinInSSL[i]; EmailClient.SendCompleted += new SendCompletedEventHandler(EmailClient_SendCompleted); if (Username.Length > 0 && Pwd.Length > 0) { NetworkCredential SMTPUserInfo = new NetworkCredential(Username, Pwd); EmailClient.Credentials = SMTPUserInfo; } FPinOutSuccess.SliceCount = SpreadMax; try { string Message = FPinInMessage[i]; string Subject = FPinInSubject[i]; //Get the Deault Encoding Bytes byte[] BytesMessage = Encoding.Default.GetBytes(Message); byte[] BytesSubject = Encoding.Default.GetBytes(Subject); MailMessage mail = new MailMessage(FPinInFrom[i], FPinInTo[i]); //Convert the Incomming Message to the corresponding encoding switch (FEmailEncoding[i].Index) { case (0): mail.BodyEncoding = mail.SubjectEncoding = Encoding.Default; break; case (1): mail.BodyEncoding = mail.SubjectEncoding = Encoding.ASCII; Message = Encoding.ASCII.GetString(BytesMessage); Subject = Encoding.ASCII.GetString(BytesSubject); break; case (2): mail.BodyEncoding = mail.SubjectEncoding = Encoding.UTF8; Message = Encoding.UTF8.GetString(BytesMessage); Subject = Encoding.UTF8.GetString(BytesSubject); break; case (3): mail.BodyEncoding = mail.SubjectEncoding = Encoding.UTF32; Message = Encoding.UTF32.GetString(BytesMessage); Subject = Encoding.UTF32.GetString(BytesSubject); break; case (4): mail.BodyEncoding = mail.SubjectEncoding = Encoding.Unicode; Message = Encoding.Unicode.GetString(BytesMessage); Subject = Encoding.Unicode.GetString(BytesSubject); break; default: mail.BodyEncoding = mail.SubjectEncoding = Encoding.Default; break; } mail.Subject = Subject; mail.Body = Message; mail.IsBodyHtml = FPinInIsHtml[i]; if (File.Exists(FPinInAttachment[i])) { Attachment Attachment = new Attachment(FPinInAttachment[i]); ContentDisposition Disposition = Attachment.ContentDisposition; Disposition.Inline = false; mail.Attachments.Add(Attachment); } EmailClient.SendAsync(mail, i); } catch (Exception ex) { FLogger.Log(LogType.Error, ex.Message); } finally { EmailClient = null; } } } } else { this.FPinOutSuccess.SliceCount = 0; } if (!String.IsNullOrEmpty(FError)) { FLogger.Log(LogType.Debug, FError); FError = ""; } }
/// <summary> /// 发送邮件 /// </summary> /// <returns>发送是否成功</returns> public bool Send() { try { MailMessage msg = new MailMessage(); msg.From = new MailAddress(m_From); msg.Subject = m_Subject; //邮件正文 msg.Body = m_Body; char[] ch = { ',' }; if (!string.IsNullOrEmpty(m_To)) { string[] address = m_To.Split(ch, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < address.Length; i++) { MailAddress toAddress = new MailAddress(address[i]); msg.To.Add(toAddress); } } if (!string.IsNullOrEmpty(m_Cc)) { string[] addressCc = m_Cc.Split(ch, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < addressCc.Length; i++) { MailAddress toAddress = new MailAddress(addressCc[i]); msg.CC.Add(toAddress); } } if (!string.IsNullOrEmpty(m_Bcc)) { string[] addressBcc = m_Bcc.Split(ch, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < addressBcc.Length; i++) { MailAddress toAddress = new MailAddress(addressBcc[i]); msg.Bcc.Add(toAddress); } } //內容是否未HTML格式 msg.IsBodyHtml = m_IsBodyHtml; //获取所有邮件附件 char[] cr = { ';' }; string[] file = m_File.Split(cr); for (int n = 0; n < file.Length; n++) { if (file[n] != "") { //附件对象 Attachment data = new Attachment(file[n], MediaTypeNames.Application.Octet); //附件资料 ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file[n]); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file[n]); disposition.ReadDate = System.IO.File.GetLastAccessTime(file[n]); //加入邮件附件 msg.Attachments.Add(data); } } //使用简单邮件传输协议来传送邮件 SmtpClient sendMail = new SmtpClient(); //发送邮件的服务器名或地址 sendMail.Host = m_Host; sendMail.Port = m_Port; //验证发件人的身份 sendMail.Credentials = new NetworkCredential(m_UserName, m_Password); //处理待发送邮件的方法 sendMail.DeliveryMethod = SmtpDeliveryMethod.Network; sendMail.EnableSsl = m_Ssl; //发送邮件 sendMail.Send(msg); return(true); } catch (Exception ex) { throw new Exception("EMail发送失败" + ex); } }
public void SetCreateDateViaParameters_WithInvalidDate_ShouldThrow() { var cd = new ContentDisposition("inline"); Assert.Throws<FormatException>(() => { cd.Parameters["creation-date"] = InvalidDate; //string date = cd.Parameters["creation-date"]; }); }
public virtual void ParseFromBase64(IMessageReader reader, ContentType contentType, ContentDisposition contentDisposition, string boundary) { byte[] buffer; Label_0000: buffer = reader.ReadLine(); if (!reader.EndOfMessage) { switch (BoundaryChecker.CheckBoundary(buffer, boundary)) { case EBoundaryType.NotBoundary: { byte[] data = MailMessageRFCDecoder.DecodeFromBase64(buffer); this.ContentWriter.Write(data); goto Label_0000; } case EBoundaryType.Final: this.RaiseFinalBoundaryReached(); break; } } }
public void GetCustomerParameterThatIsNotSet_ShouldReturnNull() { var cd = new ContentDisposition("inline"); Assert.Null(cd.Parameters["doesnotexist"]); Assert.Equal("inline", cd.DispositionType); Assert.True(cd.Inline); }
public virtual IPart ParsePart(IMessageReader reader, string contentId, ContentType contentType, ContentDisposition contentDisposition, EContentTransferEncoding contentTransferEncoding, string uid, string attachmentDirectory, string boundary, PopMessage parentMessage) { if (PartUtils.IsMultipart(contentType)) { MultiPartParser parser = new MultiPartParser(); parser.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); return(parser.Parse(reader, contentTransferEncoding, boundary, uid, attachmentDirectory, parentMessage, contentType)); } if (PartUtils.IsTextPart(contentType, contentDisposition)) { string charset = contentType.Attributes.ContainsKey("charset") ? contentType.Attributes["charset"] : "us-ascii"; TextPartParser parser2 = new TextPartParser(charset); parser2.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); return(parser2.Parse(reader, contentType, contentDisposition, contentTransferEncoding, boundary)); } if (PartUtils.IsMessagePart(contentType) && (contentType.SubType == "delivery-status")) { MessageDeliveryStatusPartParser parser3 = new MessageDeliveryStatusPartParser(); parser3.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); return(parser3.Parse(reader, contentType, contentDisposition, contentTransferEncoding, boundary)); } if (PartUtils.IsMessagePart(contentType) && (contentType.SubType == "disposition-notification")) { MessageDispositionNotificationPartParser parser4 = new MessageDispositionNotificationPartParser(); parser4.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); return(parser4.Parse(reader, contentType, contentDisposition, contentTransferEncoding, boundary)); } if (PartUtils.IsMessagePart(contentType)) { MessagePartParser parser5 = new MessagePartParser(); parser5.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); return(parser5.Parse(reader, contentType, contentDisposition, contentTransferEncoding, boundary, uid, attachmentDirectory)); } attachmentDirectory = Path.Combine(attachmentDirectory, MailClient.MessageFolderPrefix + IOUtil.FormatFileSystemName(uid)); ContentPartParser parser6 = new ContentPartParser(attachmentDirectory); parser6.FinalBoundaryReached += new EventHandler(this.childParser_FinalBoundaryReached); ContentPart part2 = (ContentPart)parser6.Parse(reader, contentType, contentDisposition, contentTransferEncoding, boundary); IPart part = part2; Attachment attachment = new Attachment(part2.DiskFilename, contentId, contentType, attachmentDirectory, part2.Size) { DiskFilename = part2.DiskFilename, TransferFilename = part2.TransferFilename, AttachmentDirectory = attachmentDirectory, ContentID = contentId, ContentType = contentType }; if (!attachment.TransferFilenameExtension.Equals(".octet-stream", StringComparison.OrdinalIgnoreCase)) { parentMessage.Attachments.Add(attachment); } return(part); }
public void SetDispositionViaConstructor_ShouldSetCorrectly_AndRespectCustomValues() { var cd = new ContentDisposition("inline; creation-date=\"" + ValidDateGmtOffset + "\"; X-Test=\"value\""); Assert.Equal("inline", cd.DispositionType); Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate); }
public IActionResult DescargarArchivo([FromQuery(Name = "path")] string path, [FromQuery(Name = "name")] string name) { DescargarArchivoRequestDTO response = new DescargarArchivoRequestDTO(); RequestDescargarArchivoDTO request = new RequestDescargarArchivoDTO(); request.PathFile = path; request.ArchivoVisual = name; try { response.Result.Data = _SocioDocumentoService.DescargarArchivo(request); response.Result.Success = true; string extension = Path.GetExtension(request.PathFile); Response.Clear(); switch (extension) { case ".docx": Response.Headers.Add("Content-type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); break; case ".jpg": Response.Headers.Add("Content-type", "image/jpeg"); break; case ".png": Response.Headers.Add("Content-type", "image/png"); break; case ".pdf": Response.Headers.Add("Content-type", "application/pdf"); break; case ".xls": Response.Headers.Add("Content-type", "application/vnd.ms-excel"); break; case ".xlsx": Response.Headers.Add("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); break; case ".doc": Response.Headers.Add("Content-type", "application/msword"); break; } var contentDispositionHeader = new ContentDisposition() { FileName = request.ArchivoVisual, DispositionType = "attachment" }; Response.Headers.Add("Content-Length", response.Result.Data.archivoBytes.Length.ToString()); Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString()); Response.Body.WriteAsync(response.Result.Data.archivoBytes); } catch (ResultException ex) { response.Result = new Result() { Success = true, ErrCode = ex.Result.ErrCode, Message = ex.Result.Message }; } catch (Exception ex) { response.Result = new Result() { Success = false, Message = "Ocurrio un problema en el servicio, intentelo nuevamente." }; } return(null); }
public void CultureSensitiveSetDateViaProperty_ShouldPersistToProprtyAndParametersCollectionAndRespectKindProperty() { CultureInfo origCulture = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo("zh"); var cd = new ContentDisposition("inline"); var date = new DateTime(2011, 6, 8, 15, 34, 07, DateTimeKind.Unspecified); cd.CreationDate = date; Assert.Equal("Wed, 08 Jun 2011 15:34:07 -0000", cd.Parameters["creation-date"]); Assert.Equal(date, cd.CreationDate); Assert.Equal("inline; creation-date=\"Wed, 08 Jun 2011 15:34:07 -0000\"", cd.ToString()); } finally { CultureInfo.CurrentCulture = origCulture; } }
public void SetAndResetDateViaParameters_ShouldWorkCorrectly() { var cd = new ContentDisposition("inline"); cd.Parameters["creation-date"] = ValidDateUnspecified; Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind); Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]); cd.Parameters["creation-date"] = ValidDateTimeLocal; Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]); Assert.Equal(ValidDateTimeLocal, cd.Parameters["Creation-Date"]); }
public static void ConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); var contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); }
/*Porque voce está ? vc tem uma demanda solicitada pelo Saulo, Cassia ou Deus? * se nao tem , nao mude nada nessa classe, pois podera cair sobre você uma terrivel maldição * se vc leu isso, vc está tendo uma chance de nao sofrer isso * * Porém se vc teve a solicitação das pessoas acima Leia descrição do que essa classe faz * * 1ª no metodo NeedSendToday recebe o parametro -1 que é a quantidade de Dias sem enviar o email, e vc ja percebeu aqui que * essa classe manda email, nao so manda como envia com anexo, esse anexo é um xls, XLS NAO UM CSV. * com as ocorrencias do Dia para empresas do grupo ELG , ele manda para 3 empresas. * * */ public void Processar(Empresas empresa) { WriteToAnEventLog log = new WriteToAnEventLog(); if (NeedSendToday.isNow(-1, empresa.relType, 21)) { var Ocorrencias = new List <OcorrenciaConhecimento>(); try { Ocorrencias = GenerateCSV(empresa.CNPJ); if (Ocorrencias != null && Ocorrencias.Count() != 0) { var EmailToSend = NeedSendToday.GetEmailByConhecimentoUkey(Ocorrencias.FirstOrDefault().UkeyConhecimento); var body = @" <strong>Atenção:</strong> Este é um envio de e-mail automático via sistema e não deve ser respondido. Qualquer dúvida, entre em contato diretamente com a Daytona Express "; using (var smtpClient = new SmtpClient("mail.daytonaexpress.com.br")) { smtpClient.UseDefaultCredentials = false; smtpClient.Host = "mail.daytonaexpress.com.br"; smtpClient.Port = 587; smtpClient.EnableSsl = false; smtpClient.Credentials = new NetworkCredential("*****@*****.**", "dayt@011"); var emailMensage = new MailMessage { IsBodyHtml = true, From = new MailAddress("*****@*****.**"), Body = body, Subject = "Informativo de Ocorrência", }; emailMensage.To.Add(new MailAddress("*****@*****.**")); emailMensage.To.Add(new MailAddress("*****@*****.**")); emailMensage.To.Add(new MailAddress("*****@*****.**")); foreach (var email in empresa.emails) { emailMensage.To.Add(new MailAddress(email)); } Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = File.GetCreationTime(attachmentFilename); disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename); disposition.ReadDate = File.GetLastAccessTime(attachmentFilename); disposition.FileName = Path.GetFileName(attachmentFilename); disposition.Size = new FileInfo(attachmentFilename).Length; disposition.DispositionType = DispositionTypeNames.Attachment; emailMensage.Attachments.Add(attachment); smtpClient.Send(emailMensage); } foreach (var OcorrenciaConhecimento in Ocorrencias.Where(x => x.LogRegister == 1).ToList()) { var _cmd = "INSERT INTO OCORRENCIAS_ENVIADAS_ENTRADA_ENTREGA VALUES(@SEQ,'@UKEYCONHECIMENTO',@CODIGO,@STATUS,CONVERT(DATETIME,'@DATA',120),'@MENSAGEM','@TYPEREL')"; _cmd = _cmd.Replace("@SEQ", OcorrenciaConhecimento.Seq.ToString()); _cmd = _cmd.Replace("@UKEYCONHECIMENTO", OcorrenciaConhecimento.UkeyConhecimento); _cmd = _cmd.Replace("@CODIGO", OcorrenciaConhecimento.CodigoOcorrencia.ToString()); _cmd = _cmd.Replace("@STATUS", "1"); _cmd = _cmd.Replace("@TYPEREL", empresa.relType); _cmd = _cmd.Replace("@DATA", String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now)); _cmd = _cmd.Replace("@MENSAGEM", "Enviado Ok"); ExecSql.execsqlDr(_cmd); } } } catch (Exception e) { log.RegistraLog("Erro Processa grupo ELG" + e.StackTrace, 3); } } }
public static void Inline_Roundtrip() { var cd = new ContentDisposition(); Assert.False(cd.Inline); cd.Inline = true; Assert.True(cd.Inline); cd.Inline = false; Assert.False(cd.Inline); Assert.Empty(cd.Parameters); }
public void EnviarCorreo(Prioridad prioridad) { MailMessage mail = new MailMessage(); String[] emails = EmailDestino.Split(';'); foreach (String email in emails) { if (!email.Trim().Equals("")) { mail.To.Add(email); } } if (archivosAdjuntos != null) { foreach (Adjunto adjunto in archivosAdjuntos) { Attachment data = new Attachment(adjunto.Stream, MediaTypeNames.Application.Octet); ContentDisposition disposition = data.ContentDisposition; disposition.FileName = adjunto.NombreArchivo; mail.Attachments.Add(data); } } String noReply = "*****@*****.**"; if (EmailDefault != null) { noReply = EmailDefault; } mail.From = new MailAddress(noReply, NombreAMostrar, System.Text.Encoding.UTF8); mail.Subject = Asunto; mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = ContenidoHTML; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.IsBodyHtml = true; if (prioridad == Prioridad.Alta) { mail.Priority = MailPriority.High; } else if (prioridad == Prioridad.Normal) { mail.Priority = MailPriority.Normal; } else if (prioridad == Prioridad.Baja) { mail.Priority = MailPriority.Low; } SmtpClient client = new SmtpClient(); String pass = "******"; if (ContraDefault != null) { pass = ContraDefault; } client.Credentials = new System.Net.NetworkCredential(noReply, pass); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; try { client.Send(mail); } catch (Exception ex) { throw new Exception(ex.Message); } }
public static void Size_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal(-1, cd.Size); Assert.Empty(cd.Parameters); cd.Size = 42; Assert.Equal(42, cd.Size); Assert.Equal(1, cd.Parameters.Count); }
/// <summary> /// Interpreta la disposición de la sección /// </summary> /// <example> /// Content-Disposition: attachment; filename="N35MQ55Z.pdf" /// </example> private static ContentDisposition ParseContentDisposition(Header objHeader) { ContentDisposition objDisposition = new ContentDisposition(); // Si tenemos una disposición en el valor ... objDisposition.ContentDispositionDefinition = objHeader.SearchValue(Header.cnstStrContentDisposition); objDisposition.FileName = objHeader.SearchValue(Header.cnstStrFileName); // Devuelve la disposición de la sección return objDisposition; }
private void WriteFileToHttpContext(string FileName, ContentDisposition contentDisposition) { var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; HttpContext.Current.Server.ScriptTimeout = int.MaxValue; var objResponse = HttpContext.Current.Response; objResponse.ClearContent(); objResponse.ClearHeaders(); switch (contentDisposition) { case ContentDisposition.Attachment: objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + Path.GetFileName(FileName) + "\""); break; case ContentDisposition.Inline: objResponse.AppendHeader("content-disposition", "inline; filename=\"" + Path.GetFileName(FileName) + "\""); break; default: throw new ArgumentOutOfRangeException("contentDisposition"); } //objResponse.AppendHeader("Content-Length", File.get.ToString()); objResponse.ContentType = FileManager.Instance.GetContentType(Path.GetExtension(FileName).Replace(".", "")); try { Response.WriteFile(FileName); } catch (Exception ex) { //Logger.Error(ex); objResponse.Write("Error : " + ex.Message); } objResponse.Flush(); objResponse.End(); HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; }
public static string EnviarCorreoConAdjunto(string strParamAsunto, string strParamMensaje, string strParamDestinatarios, string strParamArchivo) { //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); strParamDestinatarios = strParamDestinatarios.Replace(';', ','); string hostMail = "smtp.live.com"; int puertoHostMail = 25; string credentialMailUser = "******"; string credentialMailPwd = "ing4lv4r01042418697"; //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.To.Add(strParamDestinatarios); string strMensaje = "<HR SIZE=5 color=#0000ff NOSHADE> </BR><P><P><b>"; strMensaje += strParamMensaje; strMensaje += "</b></BR><P><P><HR SIZE=5 color=#0000ff NOSHADE> <P><b>NOTA: </b>Favor no responder, este mensaje es generado automáticamente por contabilidad de la FECP."; mmsg.Subject = strParamAsunto; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje //mmsg.Bcc.Add("*****@*****.**"); //Opcional //Cuerpo del Mensaje mmsg.Body = strMensaje; mmsg.Priority = MailPriority.High; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = true; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress(credentialMailUser); /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(hostMail, puertoHostMail); cliente.Credentials = new System.Net.NetworkCredential(credentialMailUser, credentialMailPwd); cliente.EnableSsl = true; //PARA ENVIAR ARCHIVO ADJUNTO if (!string.IsNullOrEmpty(strParamArchivo)) { //Create the file attachment for this e-mail message. using (Attachment data = new Attachment(strParamArchivo, MediaTypeNames.Application.Octet)) { ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(strParamArchivo); disposition.ModificationDate = System.IO.File.GetLastWriteTime(strParamArchivo); disposition.ReadDate = System.IO.File.GetLastAccessTime(strParamArchivo); mmsg.Attachments.Add(data); try { cliente.Send(mmsg); return("Mensajes enviados con exito."); } catch (Exception) { throw; } } } else { try { cliente.Send(mmsg); return("Mensajes enviados con exito."); } catch (Exception) { return("Ocurrio un problema al intentar enviar el mensaje, contactese con el administrador del sistema"); } } }
public EmailMessage(string recipients, string subject, string body, string[] files) { From = new MailAddress(Parameters.FROM, App.Name, Encoding.UTF8); To.Add(recipients.Replace(';', ',')); // this.CC // this.Bcc // this.ReplyToList; // this.IsBodyHtml = true; // this.Priority = MailPriority.High; string mode = Parameters.MODE; if (subject.Length > 0) { int m = mode.IndexOf(subject[0]); if (m > -1) { Subject = SubjBuilder(m, subject); } else { Subject = subject; } } if (body.Length > 0) { if (mode.IndexOf(body[0]) > -1) { string list = Parameters.LIST; string[] bodyList = body.Split(list.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string item in bodyList) { int m = mode.IndexOf(item[0]); if (m > -1) { Body += BodyBuilder(m, item); } } } else { Body = body; } } foreach (string file in files) { FileInfo fi = new FileInfo(file.Trim()); if (fi.Exists) { Attachment attachment = new Attachment(fi.FullName); ContentDisposition disposition = attachment.ContentDisposition; disposition.CreationDate = fi.CreationTime; disposition.ModificationDate = fi.LastWriteTime; disposition.ReadDate = fi.LastAccessTime; Attachments.Add(attachment); } else { Trace.TraceWarning("Attachment file " + fi.FullName + " not found!"); } } }
/// <summary> /// Parses a the value for the header Content-Disposition to a <see cref="ContentDisposition"/> object. /// </summary> /// <param name="headerValue">The value to be parsed</param> /// <returns>A <see cref="ContentDisposition"/> object</returns> /// <exception cref="ArgumentNullException">If <paramref name="headerValue"/> is <see langword="null"/></exception> public static ContentDisposition ParseContentDisposition(string headerValue) { if (headerValue == null) { throw new ArgumentNullException("headerValue"); } // See http://www.ietf.org/rfc/rfc2183.txt for RFC definition // Create empty ContentDisposition - we will fill in details as we read them ContentDisposition contentDisposition = new ContentDisposition(); // Now decode the parameters List <KeyValuePair <string, string> > parameters = Rfc2231Decoder.Decode(headerValue); foreach (KeyValuePair <string, string> keyValuePair in parameters) { string key = keyValuePair.Key.ToUpperInvariant().Trim(); string value = keyValuePair.Value; switch (key) { case "": // This is the DispisitionType - it has no key since it is the first one // and has no = in it. contentDisposition.DispositionType = value; break; // The correct name of the parameter is filename, but some emails also contains the parameter // name, which also holds the name of the file. Therefore we use both names for the same field. case "NAME": case "FILENAME": // The filename might be in qoutes, and it might be encoded-word encoded contentDisposition.FileName = EncodedWord.Decode(Utility.RemoveQuotesIfAny(value)); break; case "CREATION-DATE": // Notice that we need to create a new DateTime because of a failure in .NET 2.0. // The failure is: you cannot give contentDisposition a DateTime with a Kind of UTC // It will set the CreationDate correctly, but when trying to read it out it will throw an exception. // It is the same with ModificationDate and ReadDate. // This is fixed in 4.0 - maybe in 3.0 too. // Therefore we create a new DateTime which have a DateTimeKind set to unspecified DateTime creationDate = new DateTime(Rfc2822DateTime.StringToDate(Utility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.CreationDate = creationDate; break; case "MODIFICATION-DATE": DateTime midificationDate = new DateTime(Rfc2822DateTime.StringToDate(Utility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.ModificationDate = midificationDate; break; case "READ-DATE": DateTime readDate = new DateTime(Rfc2822DateTime.StringToDate(Utility.RemoveQuotesIfAny(value)).Ticks); contentDisposition.ReadDate = readDate; break; case "SIZE": contentDisposition.Size = int.Parse(Utility.RemoveQuotesIfAny(value), CultureInfo.InvariantCulture); break; default: if (key.StartsWith("X-")) { contentDisposition.Parameters.Add(key, Utility.RemoveQuotesIfAny(value)); break; } throw new ArgumentException("Unknown parameter in Content-Disposition. Ask developer to fix! Parameter: " + key); } } return(contentDisposition); }
private void StartSection(string section, ContentType sectionContentType, TransferEncoding transferEncoding, ContentDisposition contentDisposition) { SendData(String.Format("--{0}", section)); SendHeader("content-type", sectionContentType.ToString()); SendHeader("content-transfer-encoding", GetTransferEncodingName(transferEncoding)); if (contentDisposition != null) { SendHeader("content-disposition", contentDisposition.ToString()); } SendData(string.Empty); }
protected abstract IPart CreatePart(ContentType contentType, ContentDisposition contentDisposition);
public static void ExportToExcel(this IEnumerable <DataTable> dataTables, HttpResponse response, string fileName, ContentDisposition contentDisposition, SaveOptions saveOptions) { dataTables.ExportToExcel().Save(response, fileName, contentDisposition, saveOptions); }
public virtual void ParseFromQuotedPrintable(IMessageReader reader, ContentType contentType, ContentDisposition contentDisposition, string boundary) { byte[] buffer; bool flag = false; byte[] data = new byte[] { 13, 10 }; Label_0019: buffer = reader.ReadLine(); if (!reader.EndOfMessage) { switch (BoundaryChecker.CheckBoundary(buffer, boundary)) { case EBoundaryType.NotBoundary: { byte[] buffer2; if (flag) { this.ContentWriter.Write(data); } if ((buffer.Length > 0) && (buffer[buffer.Length - 1] == 0x3d)) { buffer2 = new byte[buffer.Length - 1]; Array.Copy(buffer, buffer2, (int)(buffer.Length - 1)); flag = false; } else { buffer2 = buffer; flag = true; } byte[] buffer4 = MailMessageRFCDecoder.DecodeFromQuotedPrintable(buffer2); this.ContentWriter.Write(buffer4); goto Label_0019; } case EBoundaryType.Final: this.RaiseFinalBoundaryReached(); break; } } }
/// <summary> /// 发送邮件 /// </summary> /// <param name="args">邮件信息:JSON数组。如:[{"to":"收件人地址列表","cc":"抄送人地址列表","bcc":"密送人地址列表","subject":"邮件标题","body":"邮件内容","file":"附件地址"},……]</param> public static dynamic SendMail(dynamic args, bool sl = false, int timeout = 0) { SmtpClient client = new SmtpClient(); client.Host = Smtp; try { client.Port = SmtpPort; if (SmtpPort == 465) { sl = true; } }catch (Exception ex) { client.Port = 25; } client.EnableSsl = sl; //client.Timeout = 18000;//timeout; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; //验证发件人凭证 client.Credentials = new System.Net.NetworkCredential(MailAddress, MailPassWord); MailMessage mm; foreach (dynamic item in args) { mm = new MailMessage(); mm.From = new MailAddress(MailAddress); string[] to = null; string[] cc = null; string[] bcc = null; string subject = ""; string body = ""; string[] SUpFile = null; try { Type type = item.GetType(); if (type.Name == "JObject") { subject = item["subject"]; body = item["body"]; //设置发件人地址 to = item["to"].ToString().Split(','); //设置抄送人地址 cc = item["cc"].ToString().Split(','); //设置密送人地址 bcc = item["bcc"].ToString().Split(','); //设置待发送文件 SUpFile = item["file"].ToString().Split(','); } else { subject = item.subject; body = item.body; //设置发件人地址 to = item.to.ToString().Split(','); //设置抄送人地址 cc = item.cc.ToString().Split(','); //设置密送人地址 bcc = item.bcc.ToString().Split(','); SUpFile = item.file.ToString().Split(','); } //设置收件人地址 foreach (string itemto in to) { if (!string.IsNullOrEmpty(itemto)) { mm.To.Add(itemto); } } //设置抄送人 foreach (string itemcc in cc) { if (!string.IsNullOrEmpty(itemcc)) { mm.CC.Add(itemcc); } } //设置密送人 foreach (string itembcc in bcc) { if (!string.IsNullOrEmpty(itembcc)) { mm.Bcc.Add(itembcc); } } foreach (string file in SUpFile) { if (string.IsNullOrEmpty(file)) { continue; } //将文件进行转换成Attachments Attachment data = new Attachment(file, MediaTypeNames.Application.Octet); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); mm.Attachments.Add(data); System.Net.Mime.ContentType ctype = new System.Net.Mime.ContentType(); } mm.Subject = subject; mm.Body = body; mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm); }catch (Exception ex) { return(new { status = false, message = ex.Message }); } } return(new { status = true, message = "" }); }
/// <summary> /// 发送邮件 /// </summary> /// <returns>发送是否成功</returns> public bool Send() { try { //获取所有的收件人地址 char[] ch = { ';' }; string[] address = m_To.Split(ch); string[] CCaddress = m_CC.Split(ch); MailAddressCollection allAddress = new MailAddressCollection(); //发件人地址 MailAddress fromAddress = new MailAddress(m_From); MailMessage msg = new MailMessage(); msg.From = fromAddress; for (int i = 0; i < address.Length; i++) { //收件人地址 msg.To.Add(address[i]); } //抄送人地址 for (int i = 0; i < CCaddress.Length; i++) { //收件人地址 msg.CC.Add(CCaddress[i]); } //MailAddress toAddress = new MailAddress(TO); //抄送人地址 //MailAddress CCAddress = new MailAddress(CCaddress[i]); //MailAddress CCAddress = new MailAddress(CC); //定义邮件消息 //MailMessage msg = new MailMessage(fromAddress, allAddress); ///定义抄送人 //msg.CC.Add(CCAddress); //邮件标题 msg.Subject = m_Subject; //邮件正文 msg.Body = m_Body; msg.IsBodyHtml = true; //获取所有邮件附件 char[] cr = { ';' }; string[] file = m_File.Split(cr); for (int n = 0; n < file.Length; n++) { if (file[n] != "") { //附件对象 Attachment data = new Attachment(file[n], MediaTypeNames.Application.Octet); //附件资料 ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file[n]); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file[n]); disposition.ReadDate = System.IO.File.GetLastAccessTime(file[n]); //加入邮件附件 msg.Attachments.Add(data); } } //使用简单邮件传输协议来传送邮件 SmtpClient sendMail = new SmtpClient(); //发送邮件的服务器名或地址 sendMail.Host = m_Host; //验证发件人的身份 sendMail.Credentials = new NetworkCredential(m_UserName, m_Password); //处理待发送邮件的方法 sendMail.DeliveryMethod = SmtpDeliveryMethod.Network; //发送邮件 sendMail.Send(msg); //} return(true); } catch (Exception ex) { return(false); } }
//发送按钮的单击事件 private void btnSend_Click(object sender, EventArgs e) { try { //确定smtp服务器地址。实例化一个Smtp客户端 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(cmbBoxSMTP.Text); //生成一个发送地址 string strFrom = string.Empty; //if (cmbBoxSMTP.SelectedText == "smtp.163.com") strFrom = txtUserName.Text + "@163.com"; //else // strFrom = txtUserName.Text + "@gmail.com"; //构造一个发件人地址对象 MailAddress from = new MailAddress(strFrom, txtDisplayName.Text, Encoding.UTF8); //构造一个收件人地址对象 MailAddress to = new MailAddress(txtEmail.Text, txtToName.Text, Encoding.UTF8); //构造一个Email的Message对象 MailMessage message = new MailMessage(from, to); //为 message 添加附件 foreach (TreeNode treeNode in treeViewFileList.Nodes) { //得到文件名 string fileName = treeNode.Text; //判断文件是否存在 if (File.Exists(fileName)) { //构造一个附件对象 Attachment attach = new Attachment(fileName); //得到文件的信息 ContentDisposition disposition = attach.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(fileName); disposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName); disposition.ReadDate = System.IO.File.GetLastAccessTime(fileName); //向邮件添加附件 message.Attachments.Add(attach); } else { MessageBox.Show("文件" + fileName + "未找到!"); } } //添加邮件主题和内容 message.Subject = txtSubject.Text; message.SubjectEncoding = Encoding.UTF8; message.Body = rtxtBody.Text; message.BodyEncoding = Encoding.UTF8; //设置邮件的信息 client.DeliveryMethod = SmtpDeliveryMethod.Network; message.BodyEncoding = System.Text.Encoding.UTF8; message.IsBodyHtml = false; //如果服务器支持安全连接,则将安全连接设为true。 //gmail支持,163不支持,如果是gmail则一定要将其设为true if (cmbBoxSMTP.SelectedText == "smpt.163.com") { client.EnableSsl = false; } else { client.EnableSsl = true; } //设置用户名和密码。 //string userState = message.Subject; client.UseDefaultCredentials = false; string username = txtUserName.Text; string passwd = txtPassword.Text; //用户登陆信息 NetworkCredential myCredentials = new NetworkCredential(username, passwd); client.Credentials = myCredentials; //发送邮件 client.Send(message); //提示发送成功 MessageBox.Show("发送成功!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs) { if (asyncCompletedEventArgs.Cancelled) { return; } try { if (asyncCompletedEventArgs.Error != null) { throw asyncCompletedEventArgs.Error; } if (_args.CheckSum != null) { CompareChecksum(_tempFile, _args.CheckSum); } ContentDisposition contentDisposition = null; if (_webClient.ResponseHeaders["Content-Disposition"] != null) { contentDisposition = new ContentDisposition(_webClient.ResponseHeaders["Content-Disposition"]); } var fileName = string.IsNullOrEmpty(contentDisposition?.FileName) ? Path.GetFileName(_webClient.ResponseUri.LocalPath) : contentDisposition.FileName; var tempPath = Path.Combine( string.IsNullOrEmpty(AutoUpdater.DownloadPath) ? Path.GetTempPath() : AutoUpdater.DownloadPath, fileName); if (File.Exists(tempPath)) { File.Delete(tempPath); } File.Move(_tempFile, tempPath); string installerArgs = null; if (!string.IsNullOrEmpty(_args.InstallerArgs)) { installerArgs = _args.InstallerArgs.Replace("%path%", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)); } var processStartInfo = new ProcessStartInfo { FileName = tempPath, UseShellExecute = true, Arguments = installerArgs }; var extension = Path.GetExtension(tempPath); if (extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { string installerPath = Path.Combine(Path.GetDirectoryName(tempPath), "ZipExtractor.exe"); File.WriteAllBytes(installerPath, Properties.Resources.ZipExtractor); string executablePath = Process.GetCurrentProcess().MainModule.FileName; string extractionPath = Path.GetDirectoryName(executablePath); if (!string.IsNullOrEmpty(AutoUpdater.InstallationPath) && Directory.Exists(AutoUpdater.InstallationPath)) { extractionPath = AutoUpdater.InstallationPath; } StringBuilder arguments = new StringBuilder($"\"{tempPath}\" \"{extractionPath}\" \"{executablePath}\""); string[] args = Environment.GetCommandLineArgs(); for (int i = 1; i < args.Length; i++) { if (i.Equals(1)) { arguments.Append(" \""); } arguments.Append(args[i]); arguments.Append(i.Equals(args.Length - 1) ? "\"" : " "); } processStartInfo = new ProcessStartInfo { FileName = installerPath, UseShellExecute = true, Arguments = arguments.ToString() }; } else if (extension.Equals(".msi", StringComparison.OrdinalIgnoreCase)) { processStartInfo = new ProcessStartInfo { FileName = "msiexec", Arguments = $"/i \"{tempPath}\"" }; if (!string.IsNullOrEmpty(installerArgs)) { processStartInfo.Arguments += " " + installerArgs; } } if (AutoUpdater.RunUpdateAsAdmin) { processStartInfo.Verb = "runas"; } try { Process.Start(processStartInfo); } catch (Win32Exception exception) { if (exception.NativeErrorCode == 1223) { _webClient = null; } else { throw; } } } catch (Exception e) { MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Error); _webClient = null; } finally { Close(); } }
private void WriteEncodedHeader(Stream stream, ContentDisposition header) { if (String.IsNullOrEmpty(header.Value) == true) { return; } var headerBuffer = GetAsciiBytes("Content-Disposition"); var maxCharCount = 74 - headerBuffer.Length; stream.Write(headerBuffer); stream.Write(ByteData.ColonSpace);// :[white space] stream.Write(GetAsciiBytes(header.Value)); stream.WriteByte(59);// ; stream.Write(ByteData.NewLine); if (String.IsNullOrEmpty(header.FileName) == false) { if (this.FileNameEncoding == Smtp.FileNameEncoding.BestEffort) { WriteMimeParameterRfc2231EncodedValue(stream, "FileName", header.FileName); } else { WriteMimeParameter(stream, "FileName", header.FileName); } } foreach (var p in header.Parameters) { WriteMimeParameter(stream, p.Key, p.Value); } }
public object UploadFile(string folderid, Stream file, ContentType contentType, ContentDisposition contentDisposition, IEnumerable <System.Web.HttpPostedFileBase> files, bool createNewIfExist, bool storeOriginalFileFlag) { FilesSettings.StoreOriginalFiles = storeOriginalFileFlag; if (files != null && files.Any()) { if (files.Count() == 1) { //Only one file. return it var postedFile = files.First(); return(SaveFile(folderid, postedFile.InputStream, postedFile.FileName, createNewIfExist)); } //For case with multiple files return(files.Select(postedFile => SaveFile(folderid, postedFile.InputStream, postedFile.FileName, createNewIfExist)).ToList()); } if (file != null) { var fileName = "file" + MimeMapping.GetExtention(contentType.MediaType); if (contentDisposition != null) { fileName = contentDisposition.FileName; } return(SaveFile(folderid, file, fileName, createNewIfExist)); } throw new InvalidOperationException("No input files"); }
public static void Dates_RoundtripWithoutImpactingOtherDates() { var cd = new ContentDisposition(); Assert.Equal(DateTime.MinValue, cd.CreationDate); Assert.Equal(DateTime.MinValue, cd.ModificationDate); Assert.Equal(DateTime.MinValue, cd.ReadDate); Assert.Empty(cd.Parameters); DateTime dt1 = DateTime.Now; cd.CreationDate = dt1; Assert.Equal(1, cd.Parameters.Count); DateTime dt2 = DateTime.Now; cd.ModificationDate = dt2; Assert.Equal(2, cd.Parameters.Count); DateTime dt3 = DateTime.Now; cd.ReadDate = dt3; Assert.Equal(3, cd.Parameters.Count); Assert.Equal(dt1, cd.CreationDate); Assert.Equal(dt2, cd.ModificationDate); Assert.Equal(dt3, cd.ReadDate); Assert.Equal(3, cd.Parameters.Count); }
static void ExtractAttachments(TnefReader reader, BodyBuilder builder) { var attachMethod = TnefAttachMethod.ByValue; var filter = new BestEncodingFilter(); var prop = reader.TnefPropertyReader; MimePart attachment = null; int outIndex, outLength; TnefAttachFlags flags; string[] mimeType; byte[] attachData; string text; do { if (reader.AttributeLevel != TnefAttributeLevel.Attachment) { break; } switch (reader.AttributeTag) { case TnefAttributeTag.AttachRenderData: attachMethod = TnefAttachMethod.ByValue; attachment = new MimePart(); break; case TnefAttributeTag.Attachment: if (attachment == null) { break; } attachData = null; while (prop.ReadNextProperty()) { switch (prop.PropertyTag.Id) { case TnefPropertyId.AttachLongFilename: attachment.FileName = prop.ReadValueAsString(); break; case TnefPropertyId.AttachFilename: if (attachment.FileName == null) { attachment.FileName = prop.ReadValueAsString(); } break; case TnefPropertyId.AttachContentLocation: attachment.ContentLocation = prop.ReadValueAsUri(); break; case TnefPropertyId.AttachContentBase: attachment.ContentBase = prop.ReadValueAsUri(); break; case TnefPropertyId.AttachContentId: text = prop.ReadValueAsString(); var buffer = CharsetUtils.UTF8.GetBytes(text); int index = 0; if (ParseUtils.TryParseMsgId(buffer, ref index, buffer.Length, false, false, out string msgid)) { attachment.ContentId = msgid; } break; case TnefPropertyId.AttachDisposition: text = prop.ReadValueAsString(); if (ContentDisposition.TryParse(text, out ContentDisposition disposition)) { attachment.ContentDisposition = disposition; } break; case TnefPropertyId.AttachData: attachData = prop.ReadValueAsBytes(); break; case TnefPropertyId.AttachMethod: attachMethod = (TnefAttachMethod)prop.ReadValueAsInt32(); break; case TnefPropertyId.AttachMimeTag: mimeType = prop.ReadValueAsString().Split('/'); if (mimeType.Length == 2) { attachment.ContentType.MediaType = mimeType[0].Trim(); attachment.ContentType.MediaSubtype = mimeType[1].Trim(); } break; case TnefPropertyId.AttachFlags: flags = (TnefAttachFlags)prop.ReadValueAsInt32(); if ((flags & TnefAttachFlags.RenderedInBody) != 0) { if (attachment.ContentDisposition == null) { attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Inline); } else { attachment.ContentDisposition.Disposition = ContentDisposition.Inline; } } break; case TnefPropertyId.AttachSize: if (attachment.ContentDisposition == null) { attachment.ContentDisposition = new ContentDisposition(); } attachment.ContentDisposition.Size = prop.ReadValueAsInt64(); break; case TnefPropertyId.DisplayName: attachment.ContentType.Name = prop.ReadValueAsString(); break; } } if (attachData != null) { int count = attachData.Length; int index = 0; if (attachMethod == TnefAttachMethod.EmbeddedMessage) { attachment.ContentTransferEncoding = ContentEncoding.Base64; attachment = PromoteToTnefPart(attachment); count -= 16; index = 16; } else if (attachment.ContentType.IsMimeType("text", "*")) { filter.Flush(attachData, index, count, out outIndex, out outLength); attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit); filter.Reset(); } else { attachment.ContentTransferEncoding = ContentEncoding.Base64; } attachment.Content = new MimeContent(new MemoryStream(attachData, index, count, false)); builder.Attachments.Add(attachment); } break; case TnefAttributeTag.AttachCreateDate: if (attachment != null) { if (attachment.ContentDisposition == null) { attachment.ContentDisposition = new ContentDisposition(); } attachment.ContentDisposition.CreationDate = prop.ReadValueAsDateTime(); } break; case TnefAttributeTag.AttachModifyDate: if (attachment != null) { if (attachment.ContentDisposition == null) { attachment.ContentDisposition = new ContentDisposition(); } attachment.ContentDisposition.ModificationDate = prop.ReadValueAsDateTime(); } break; case TnefAttributeTag.AttachTitle: if (attachment != null && string.IsNullOrEmpty(attachment.FileName)) { attachment.FileName = prop.ReadValueAsString(); } break; case TnefAttributeTag.AttachMetaFile: if (attachment == null) { break; } // TODO: what to do with the meta data? break; case TnefAttributeTag.AttachData: if (attachment == null || attachMethod != TnefAttachMethod.ByValue) { break; } attachData = prop.ReadValueAsBytes(); if (attachment.ContentType.IsMimeType("text", "*")) { filter.Flush(attachData, 0, attachData.Length, out outIndex, out outLength); attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit); filter.Reset(); } else { attachment.ContentTransferEncoding = ContentEncoding.Base64; } attachment.Content = new MimeContent(new MemoryStream(attachData, false)); builder.Attachments.Add(attachment); break; } } while (reader.ReadNextAttribute()); }
public static void DispositionType_Roundtrip() { var cd = new ContentDisposition(); Assert.Equal("attachment", cd.DispositionType); Assert.Empty(cd.Parameters); cd.DispositionType = "hello"; Assert.Equal("hello", cd.DispositionType); cd.DispositionType = "world"; Assert.Equal("world", cd.DispositionType); Assert.Equal(0, cd.Parameters.Count); }
/// <summary> /// Appends embedded content to a message XML output. /// </summary> /// <param name="ContentId">Content ID</param> /// <param name="ContentType">Content-Type of embedded content.</param> /// <param name="ContentData">Binary encoding of content to embed.</param> /// <param name="Disposition">Content disposition.</param> /// <param name="Name">Name attribute</param> /// <param name="FileName">File-name attribute</param> /// <param name="Description">Content description.</param> /// <param name="Xml">XML output.</param> public void AppendContent(string ContentId, string ContentType, byte[] ContentData, ContentDisposition Disposition, string Name, string FileName, string Description, StringBuilder Xml) { Xml.Append("<content xmlns='"); Xml.Append(NamespaceMail); Xml.Append("' cid='"); Xml.Append(XML.Encode(ContentId)); Xml.Append("' type='"); Xml.Append(XML.Encode(ContentType)); if (Disposition != ContentDisposition.Unknown) { Xml.Append("' disposition='"); Xml.Append(XML.Encode(Disposition.ToString())); } if (!string.IsNullOrEmpty(Name)) { Xml.Append("' name='"); Xml.Append(XML.Encode(Name)); } if (!string.IsNullOrEmpty(FileName)) { Xml.Append("' fileName='"); Xml.Append(XML.Encode(FileName)); } if (!string.IsNullOrEmpty(Description)) { Xml.Append("' description='"); Xml.Append(XML.Encode(Description)); } Xml.Append("'>"); Xml.Append(Convert.ToBase64String(ContentData)); // TODO: Chunked transfer Xml.Append("</content>"); }
public void SendMail(ScheduleJob scheduleJob) { logger.Log("Sending mail..."); try { using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)) { smtp.Credentials = new NetworkCredential("*****@*****.**", "tk2QQCZky8Ug"); smtp.EnableSsl = true; //string sender = scheduleJob.SenderName.ToLower().Replace("ü", "ue").Replace('ş', 's').Replace('ı', 'i').Replace("ö", "oe").Replace("ç", "c").Replace('ğ', 'g'); string path = Path.Combine(HttpRuntime.AppDomainAppPath, "Views\\Templates\\" + scheduleJob.TemplateFile + ".cshtml"); string decodedHtml = WebUtility.HtmlDecode(scheduleJob.Body); MailMessage message = new MailMessage { From = new MailAddress("*****@*****.**", scheduleJob.SenderName, Encoding.UTF8), IsBodyHtml = true, BodyEncoding = Encoding.UTF8, SubjectEncoding = Encoding.UTF8, Body = System.IO.File.ReadAllText(path).Replace("{%body%}", decodedHtml), Subject = scheduleJob.Subject }; if (!string.IsNullOrEmpty(scheduleJob.To)) { message.To.Add(scheduleJob.To); } if (!string.IsNullOrEmpty(scheduleJob.CC)) { message.CC.Add(scheduleJob.CC); } if (!string.IsNullOrEmpty(scheduleJob.BCC)) { message.Bcc.Add(scheduleJob.BCC); } if (!string.IsNullOrEmpty(scheduleJob.Attachments)) { foreach (string attachment in scheduleJob.Attachments.Split(',')) { // Attachment is physical file path, can be edited to be relative path later // Create the file attachment for this e-mail message. System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(attachment); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(attachment); disposition.ModificationDate = System.IO.File.GetLastWriteTime(attachment); disposition.ReadDate = System.IO.File.GetLastAccessTime(attachment); // Add the file attachment to this e-mail message. message.Attachments.Add(data); } } try { smtp.Send(message); logger.Log("Mail has been sent."); } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } } } catch (Exception ex) { logger.Log(ex.ToString().Replace("\r\n", "")); } }
protected override IPart CreatePart(ContentType contentType, ContentDisposition contentDisposition) { return(new MessageDeliveryStatusPart { Text = base._contentWriter.Text }); }
public static void UseDifferentCultureAndConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse() { ContentDisposition contentDisposition = new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\""); CultureInfo origCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("zh-cn"); try { ContentDisposition contentDisposition2 = new ContentDisposition(); contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]); contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]); Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate); Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate); } finally { CultureInfo.CurrentCulture = origCulture; } }
/// <summary> /// Returns a URL that one can use to force Reporting Services /// </summary> /// <param name="report"><see cref="Report"/> instance currently loaded.</param> /// <param name="reportViewer"><see cref="ReportViewer"/> component instance containing <paramref name="report"/></param> /// <param name="contentDisposition"><paramref name="reportViewer"/> export content disposition.</param> /// <returns>String representing URL to export report using Reporting Serivces engine.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or <paramref name="reportViewer"/> is null.</exception> public static string GetReportExportUrl(Report report, ReportViewer reportViewer, ContentDisposition contentDisposition) { if (report == null) { throw new ArgumentNullException("report"); } if (reportViewer == null) { throw new ArgumentNullException("reportViewer"); } //Get the viewer instance id FieldInfo instanceIdInfo = typeof(ReportViewer).GetField("m_instanceIdentifier", BindingFlags.Instance | BindingFlags.NonPublic); String viewerInstanceId = ((Guid)instanceIdInfo.GetValue(reportViewer)).ToString("N"); //Get drill through field FieldInfo drillthroughField = typeof(Report).GetField("m_drillthroughDepth", BindingFlags.Instance | BindingFlags.NonPublic); int drillthroughDepth = (int)drillthroughField.GetValue(report); //Create query StringBuilder exportQuery = new StringBuilder(); exportQuery.AppendFormat("Mode={0}&", "true"); exportQuery.AppendFormat("ReportID={0}&", Guid.NewGuid().ToString("N")); exportQuery.AppendFormat("ControlID={0}&", viewerInstanceId); exportQuery.AppendFormat("Culture={0}&", CultureInfo.InvariantCulture.LCID.ToString(CultureInfo.InvariantCulture)); exportQuery.AppendFormat("UICulture={0}&", CultureInfo.InvariantCulture.LCID.ToString(CultureInfo.InvariantCulture)); exportQuery.AppendFormat("ReportStack={0}&", drillthroughDepth); exportQuery.AppendFormat("OpType={0}&", "Export"); exportQuery.AppendFormat("FileName={0}&", report.DisplayName); //it should be empty as we do not use either Embedded or File reports exportQuery.AppendFormat("ContentDisposition={0}&", contentDisposition); exportQuery.Append("Format="); //Build exact URL UriBuilder handlerUri = GetReportHandlerUri(); handlerUri.Query = exportQuery.ToString(); return handlerUri.Uri.PathAndQuery; }
static public void SendMail(SaveMailParam smp, StateMail userState) //Передать параметром чтобы не вызывал сообщения { MailMessage mess = null; SmtpClient client = null; try { client = new SmtpClient(smp.SMTPServer, smp.SMTPPort); client.Credentials = new NetworkCredential(smp.FromMail.Split('@')[0], smp.FromPassword); //Выключаем или включаем SSL - (например для гугла и mail должен быть включен). client.EnableSsl = smp.SSL; client.DeliveryMethod = SmtpDeliveryMethod.Network; mess = new MailMessage(); mess.From = new MailAddress(smp.FromMail, smp.DisplayName); //отображаемое имя string[] masTo = smp.ToMail.Split(';'); if (masTo.Length > 0) { for (int i = 0; i < masTo.Length; i++) { mess.To.Add(new MailAddress(masTo[i].Trim())); } } mess.Subject = smp.Tema; mess.Body = smp.Text; mess.IsBodyHtml = smp.isHTML; client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); } catch (Exception e) { if (userState != null) { if (userState.MessageBoxShow) { MessageBox.Show(e.Message); } userState.EvenWaitH.Set(); } else { MessageBox.Show(e.Message); } return; } if ((smp.FileNames != null) && (smp.FileNames.Count > 0)) { for (int i = 0; i < smp.FileNames.Count; i++) { //Теперь прикрепим файл к сообщению... try { string file = smp.FileNames[i]; // Тип файла не определен Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet); // Добавляем информацию для файла ContentDisposition disposition = attach.ContentDisposition; disposition.CreationDate = System.IO.File.GetCreationTime(file); disposition.ModificationDate = System.IO.File.GetLastWriteTime(file); disposition.ReadDate = System.IO.File.GetLastAccessTime(file); mess.Attachments.Add(attach); } catch (Exception e) { if (userState != null) { if (userState.MessageBoxShow) { MessageBox.Show(smp.FileNames[i] + " - " + e.Message); } userState.EvenWaitH.Set(); } else { MessageBox.Show(smp.FileNames[i] + " - " + e.Message); } return; } } } client.SendAsync(mess, userState); }