コード例 #1
1
        public static void SaveBinariesWithCid(string mimeMsg, string savePath, Dictionary<string, string> savedFiles)
        {
            Stream mimeMsgStream = new MemoryStream(Encoding.ASCII.GetBytes(mimeMsg));
            MimeMessage m = new MimeMessage(mimeMsgStream);

            SaveBinariesWithCid(m, savePath, savedFiles);
        }
コード例 #2
0
ファイル: MimeHeadersParser.cs プロジェクト: jbautistam/Pop3
 /// <summary>
 ///		Lee las cabeceras del mensaje
 /// </summary>
 internal static void ReadHeaders(ParserLines objParser, MimeMessage objMessage)
 {
     // Lee las cabeceras
         objMessage.Headers.AddRange(ReadHeaders(objParser));
     // Normaliza las cabeceras del mensaje
         NormalizeHeaders(objMessage);
 }
コード例 #3
0
ファイル: Encoder.cs プロジェクト: pengyancai/cs-util
 internal static BinaryWriter CreateContentBinaryWriter(MimeMessage message)
 {
     if (message.Charset == null)
     return new BinaryWriter(CreateContentWritingStream(message));
       else
     return new BinaryWriter(CreateContentWritingStream(message), message.Charset);
 }
コード例 #4
0
ファイル: Encoder.cs プロジェクト: pengyancai/cs-util
        internal static Stream CreateContentWritingStream(MimeMessage message)
        {
            var format = (message.Format ?? MimeFormat.Unspecified);

              message.Content = new MemoryStream(1024);

              return ContentEncodingStreamUtils.CreateEncodingStream(message.Content, message.TransferEncoding, format);
        }
コード例 #5
0
ファイル: Decoder.cs プロジェクト: pengyancai/cs-util
        internal static Stream CreateContentReadingStream(MimeMessage message)
        {
            if (message.Content == null)
            throw new InvalidOperationException("content is null");

              message.Content.Position = 0L;

              return ContentTransferEncoding.CreateDecodingStream(message.Content,
                                                          message.TransferEncoding);
        }
コード例 #6
0
ファイル: Decoder.cs プロジェクト: pengyancai/cs-util
        internal static BinaryReader CreateContentBinaryReader(MimeMessage message)
        {
            if (message.Content == null)
            throw new InvalidOperationException("content is null");

              message.Content.Position = 0L;

              return ContentTransferEncoding.CreateBinaryReader(message.Content,
                                                        message.TransferEncoding,
                                                        message.Charset);
        }
コード例 #7
0
ファイル: Decoder.cs プロジェクト: pengyancai/cs-util
        internal static StreamReader CreateContentTextReader(MimeMessage message)
        {
            if (message.Content == null)
            throw new InvalidOperationException("content is null");

              message.Content.Position = 0L;

              return ContentTransferEncoding.CreateTextReader(message.Content,
                                                      message.TransferEncoding,
                                                      message.Charset ?? Charsets.ISO8859_1);
        }
コード例 #8
0
ファイル: Encoder.cs プロジェクト: pengyancai/cs-util
        internal static StreamWriter CreateContentTextWriter(MimeMessage message)
        {
            if (message.TransferEncoding == ContentTransferEncodingMethod.Binary)
            throw new InvalidOperationException("can't create TextWriter from message of binary transfer encoding");

              var writer = new StreamWriter(CreateContentWritingStream(message), message.Charset ?? Charsets.ISO8859_1);

              writer.NewLine = (message.Format ?? MimeFormat.Unspecified).GetEOLString();

              return writer;
        }
コード例 #9
0
ファイル: Formatter.cs プロジェクト: pengyancai/cs-util
        public static void Format(MimeMessage message, Stream stream)
        {
            var multipart = 0 < message.SubParts.Count;

              if (multipart && message.Boundary == null)
            throw new NullReferenceException("message is multipart, but boudnary was null");

              if (!message.Headers.Contains("MIME-Version"))
            message.Headers.Insert(0, new MimeHeader("MIME-Version", "1.0"));

              if (!message.Headers.Contains("Content-Type"))
            message.Headers.Insert(1, MimeHeader.CreateContentType(message.Format,
                                                               message.MimeType ?? (multipart ? MimeType.MultipartMixed : MimeType.TextPlain),
                                                               message.Charset,
                                                               multipart ? message.Boundary : null));

              if (!message.Headers.Contains("Content-Transfer-Encoding"))
            message.Headers.Insert(1, MimeHeader.CreateContentTransferEncoding(message.Format, message.TransferEncoding));

              var textWriter = new StreamWriter(stream, Charsets.ISO8859_1);
              var eol = (message.Format ?? MimeFormat.Unspecified).GetEOLString();

              textWriter.NewLine = eol;

              foreach (var header in message.Headers) {
            textWriter.WriteLine(header.ToString());
              }

              if (multipart) {
            var delimiter = string.Format("{0}--{1}", eol, message.Boundary);

            foreach (var part in message.SubParts) {
              textWriter.WriteLine(delimiter);
              textWriter.Flush();

              Format(part, stream);
            }

            textWriter.WriteLine(string.Format("{0}--", delimiter));
            textWriter.Flush();
              }
              else {
            textWriter.WriteLine();
            textWriter.Flush();

            if (message.Content != null) {
              message.Content.WriteTo(stream);
              stream.Flush();
            }
              }
        }
コード例 #10
0
ファイル: Decoder.cs プロジェクト: pengyancai/cs-util
        internal static MimeMessage Decode(MimeMessage message)
        {
            var decodedHeaders = Decode(message.Headers);

              var decodedMessage = new MimeMessage(decodedHeaders, message.Content, message.SubParts.ConvertAll<MimeMessage>(Decode));

              decodedMessage.Charset = message.Charset;
              decodedMessage.MimeType = message.MimeType;
              decodedMessage.Boundary = message.Boundary;
              decodedMessage.TransferEncoding = message.TransferEncoding;
              decodedMessage.Disposition = message.Disposition;

              return decodedMessage;
        }
コード例 #11
0
ファイル: MimeMessageParser.cs プロジェクト: jbautistam/Pop3
        /// <summary>
        ///		Interpreta los datos de un mensaje
        /// </summary>
        public static MimeMessage Parse(string strMessage)
        {
            MimeMessage objMail = new MimeMessage();
            ParserLines objParser = new ParserLines(strMessage);
            Section objSection;

                // Interpreta las líneas recibidas
                    MimeHeadersParser.ReadHeaders(objParser, objMail);
                // Interpreta las secciones
                    objSection = ParseSections(objMail.ContentType, objParser);
                // Normaliza el correo
                    NormalizeMail(objMail, objSection);
                // Devuelve el mensaje recibido
                    return objMail;
        }
コード例 #12
0
ファイル: MimeMessageCreator.cs プロジェクト: jbautistam/Pop3
        /// <summary>
        ///		Crea la cabecera del mensaje
        /// </summary>
        public static string CreateMessage(MimeMessage objMessage, string strCharSet)
        {
            StringBuilder sbWriter = new StringBuilder();

                // Responder a ...
                    if (!string.IsNullOrEmpty(objMessage.ReplyTo.EMail))
                        sbWriter.Append("Reply-To: " + GetEMail(objMessage.ReplyTo) + cnstStrEndLine);
                // Remitente
                    if (!string.IsNullOrEmpty(objMessage.From.EMail))
                        sbWriter.Append("From: " + GetEMail(objMessage.From) + cnstStrEndLine);
                // Destinatarios
                    sbWriter.Append("To: " + CreateAddressList(objMessage.To) + cnstStrEndLine);
                    if (objMessage.CC.Count > 0)
                        sbWriter.Append("CC: " + CreateAddressList(objMessage.CC) + cnstStrEndLine);
                    if (objMessage.BCC.Count > 0)
                        sbWriter.Append("BCC: " + CreateAddressList(objMessage.BCC) + cnstStrEndLine);
                // Asunto
                    if (!string.IsNullOrEmpty(objMessage.Subject))
                        sbWriter.Append("Subject: " + LibEncoder.Encoder.Encode(LibEncoder.Encoder.EncoderType.QuotedPrintable,
                                                                                                                                        objMessage.Subject, true) + cnstStrEndLine);
                // Añade la fecha
                    sbWriter.Append("Date: " + DateTime.Now.ToUniversalTime().ToString("R") + cnstStrEndLine);
                // Añade la cabecera de emisión
                    sbWriter.Append("X-Mailer: LibMailProtocols.net" + cnstStrEndLine);
                // Añade los datos de notificación
                    //if (notification)
                    //{
                    //  if (ReplyTo.name != null && ReplyTo.name.Length != 0)
                    //           {
                    //               sb.Append("Disposition-Notification-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.name, charset) + " <" + ReplyTo.address + ">\r\n");
                    //           }
                    //  else
                    //  {
                    //               sb.Append("Disposition-Notification-To: <" + ReplyTo.address + ">\r\n");
                    //           }
                    //}

                    //if (Priority != MailPriority.Unknown)
                    //  sb.Append("X-Priority: " + ((int) Priority).ToString() + "\r\n");
                // Añade las cabeceras
                    sbWriter.Append(GetHeaders(objMessage));
                // Añade la versión MIME
                    sbWriter.Append("MIME-Version: 1.0" + cnstStrEndLine);
                    sbWriter.Append(GetMessageBody(objMessage, strCharSet));
                // Devuelve la cadena a enviar
                    return sbWriter.ToString();
        }
コード例 #13
0
ファイル: Encoder.cs プロジェクト: pengyancai/cs-util
        internal static MimeMessage Encode(MimeMessage message)
        {
            var encodedHeaders = new MimeHeaderCollection();

              foreach (var header in message.Headers) {
            encodedHeaders.Add(Encode(header));
              }

              var encodedMessage = new MimeMessage(encodedHeaders, message.Content, message.SubParts.ConvertAll<MimeMessage>(Encode));

              encodedMessage.Format = message.Format;
              encodedMessage.Charset = message.Charset;
              encodedMessage.MimeType = message.MimeType;
              encodedMessage.Boundary = message.Boundary;
              encodedMessage.TransferEncoding = message.TransferEncoding;
              encodedMessage.Disposition = message.Disposition;

              return encodedMessage;
        }
コード例 #14
0
ファイル: TnefPart.cs プロジェクト: richard2753/MimeKit
		static void ExtractRecipientTable (TnefReader reader, MimeMessage message)
		{
			var prop = reader.TnefPropertyReader;

			// Note: The RecipientTable uses rows of properties...
			while (prop.ReadNextRow ()) {
				InternetAddressList list = null;
				string name = null, addr = null;

				while (prop.ReadNextProperty ()) {
					switch (prop.PropertyTag.Id) {
					case TnefPropertyId.RecipientType:
						int recipientType = prop.ReadValueAsInt32 ();
						switch (recipientType) {
						case 1: list = message.To; break;
						case 2: list = message.Cc; break;
						case 3: list = message.Bcc; break;
						}
						break;
					case TnefPropertyId.TransmitableDisplayName:
						if (string.IsNullOrEmpty (name))
							name = prop.ReadValueAsString ();
						break;
					case TnefPropertyId.DisplayName:
						name = prop.ReadValueAsString ();
						break;
					case TnefPropertyId.EmailAddress:
						if (string.IsNullOrEmpty (addr))
							addr = prop.ReadValueAsString ();
						break;
					case TnefPropertyId.SmtpAddress:
						// The SmtpAddress, if it exists, should take precedence over the EmailAddress
						// (since the SmtpAddress is meant to be used in the RCPT TO command).
						addr = prop.ReadValueAsString ();
						break;
					}
				}

				if (list != null && !string.IsNullOrEmpty (addr))
					list.Add (new MailboxAddress (name, addr));
			}
		}
コード例 #15
0
ファイル: MimeMessageParser.cs プロジェクト: jbautistam/Pop3
 /// <summary>
 ///		Normaliza el correo
 /// </summary>
 private static void NormalizeMail(MimeMessage objMail, Section objSection)
 {
     // Normaliza la sección
         if (objSection.ContentType.Type == ContentType.ContentTypeEnum.Text)
             { objMail.Body = objSection;
                 objMail.Body.Content = Encoder.Decode(Encoder.GetEncoderType(objSection.TransferEncoding.TransferEncodingDefinition),
                                                                                             objSection.ContentType.CharSet,
                                                                                             objSection.Content, false);
             }
         else if (objSection.ContentType.Type == ContentType.ContentTypeEnum.HTML)
             { objMail.BodyHTML = objSection;
                 objMail.BodyHTML.Content = Encoder.Decode(Encoder.GetEncoderType(objSection.TransferEncoding.TransferEncodingDefinition),
                                                                                                     objSection.ContentType.CharSet,
                                                                                                     objSection.Content, false);
             }
         else if (objSection.ContentDisposition.IsAttachment)
             objMail.Attachments.Add(objSection);
     // Normaliza las secciones hija
         foreach (Section objSectionChild in objSection.Sections)
             NormalizeMail(objMail, objSectionChild);
 }
コード例 #16
0
		/// <param name="mailInfo">
		/// 
		/// @return </param>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static javax.mail.Message setCommon(MailSenderInfo mailInfo) throws javax.mail.MessagingException
		private static Message setCommon(MailSenderInfo mailInfo)
		{

			//
			// 判断是否需要身份认证
			//
			MyAuthenticator authenticator = null;
			Properties pro = mailInfo.Properties;
			if (mailInfo.Validate)
			{
				// 如果需要身份认证,则创建一个密码验证器
				authenticator = new MyAuthenticator(mailInfo.UserName, mailInfo.Password);
			}

			// 根据邮件会话属性和密码验证器构造一个发送邮件的session
			Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);

			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.FromAddress);

			// 设置邮件消息的发送者
			mailMessage.From = from;

			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(mailInfo.ToAddress);
			mailMessage.setRecipient(Message.RecipientType.TO, to);

			// 设置邮件消息的主题
			mailMessage.Subject = mailInfo.Subject;

			// 设置邮件消息发送的时间
			mailMessage.SentDate = DateTime.Now;

			return mailMessage;

		}
コード例 #17
0
ファイル: MimeHeadersParser.cs プロジェクト: jbautistam/Pop3
 /// <summary>
 ///		Normaliza las cabeceras de un correo
 /// </summary>
 private static void NormalizeHeaders(MimeMessage objMail)
 {
     foreach (Header objHeader in objMail.Headers)
         if (objHeader.Name.Equals(Header.cnstStrFrom, StringComparison.CurrentCultureIgnoreCase))
             objMail.From = new Address(DecodeQP(objHeader.Value, true));
         else if (objHeader.Name.Equals(Header.cnstStrTo, StringComparison.CurrentCultureIgnoreCase))
             objMail.To = new AddressesCollection(DecodeQP(objHeader.Value, true));
         else if (objHeader.Name.Equals(Header.cnstStrCC, StringComparison.CurrentCultureIgnoreCase))
             objMail.CC = new AddressesCollection(DecodeQP(objHeader.Value, true));
         else if (objHeader.Name.Equals(Header.cnstStrSubject, StringComparison.CurrentCultureIgnoreCase))
             objMail.Subject = DecodeQP(objHeader.Value, true);
         else if (objHeader.Name.Equals(Header.cnstStrDate, StringComparison.CurrentCultureIgnoreCase))
             objMail.Date = MimeParserHelper.GetDate(objHeader.Value);
         else if (objHeader.Name.Equals(Header.cnstStrMimeVersion, StringComparison.CurrentCultureIgnoreCase))
             objMail.MimeVersion = objHeader.Value;
         else if (objHeader.Name.Equals(Header.cnstStrID, StringComparison.CurrentCultureIgnoreCase))
             objMail.ID = objHeader.Value;
         else if (objHeader.Name.Equals(Header.cnstStrContentType, StringComparison.CurrentCultureIgnoreCase))
             objMail.ContentType = ParseContentType(objHeader);
         else if (objHeader.Name.Equals(Header.cnstStrContentTransferEncoding, StringComparison.CurrentCultureIgnoreCase))
             objMail.TransferEncoding = ParseTransferEncoding(objHeader);
 }
コード例 #18
0
        private async Task<bool> ReceiveMail(Stream reader, StreamWriter writer, string line, IPEndPoint endPoint)
        {
            IPHostEntry entry = await Dns.GetHostEntryAsync(endPoint.Address);
            MailFromResult result = await ParseMailFrom(null, reader, writer, line, endPoint);
            if (result is null)
            {
                return false;
            }
            try
            {
                string subject;
                MimeMessage msg;
                using (Stream stream = File.OpenRead(result.BackingFile))
                {
                    msg = await MimeMessage.LoadAsync(stream, true, cancelToken);
                    subject = msg.Subject;
                }
                subject = (subject ?? string.Empty).Trim();
                if (subject.Equals("unsubscribe", StringComparison.OrdinalIgnoreCase))
                {
                    UnsubscribeHandler?.Invoke(result.From.Address, subject, msg.HtmlBody);
                    return true;
                }

                // mail demon doesn't have an inbox yet, only forwarding, so see if any of the to addresses can be forwarded
                foreach (var kv in result.ToAddresses)
                {
                    foreach (MailboxAddress address in kv.Value)
                    {
                        MailDemonUser user = users.FirstOrDefault(u => u.MailAddress.Address.Equals(address.Address, StringComparison.OrdinalIgnoreCase));

                        // if no user or the forward address points to a user, fail
                        if (user == null || users.FirstOrDefault(u => u.MailAddress.Address.Equals(user.ForwardAddress.Address, StringComparison.Ordinal)) != null)
                        {
                            await writer.WriteLineAsync($"500 invalid command - user not found");
                            await writer.FlushAsync();
                        }

                        // setup forward headers
                        MailboxAddress forwardToAddress = (user.ForwardAddress ?? globalForwardAddress);
                        if (forwardToAddress == null)
                        {
                            await writer.WriteLineAsync($"500 invalid command - user not found 2");
                            await writer.FlushAsync();
                        }
                        else
                        {
                            string forwardDomain = forwardToAddress.Address.Substring(forwardToAddress.Address.IndexOf('@') + 1);

                            // create new object to forward on
                            MailFromResult newResult = new MailFromResult
                            {
                                BackingFile = result.BackingFile,
                                From = user.MailAddress,
                                ToAddresses = new Dictionary<string, IEnumerable<MailboxAddress>> { { forwardDomain, new List<MailboxAddress> { forwardToAddress } } }
                            };

                            // forward the message on and clear the forward headers
                            MailDemonLog.Info("Forwarding message, from: {0}, to: {1}, forward: {2}", result.From, address, forwardToAddress);
                            result.BackingFile = null; // we took ownership of the file

                            // send in background
                            SendMail(newResult, true, prepMsg =>
                            {
                                prepMsg.Subject = $"FW from {result.From}: {prepMsg.Subject}";
                                prepMsg.Cc.Clear();
                                prepMsg.Bcc.Clear();
                                string fromString = result.From.ToString();
                                if (prepMsg.ReplyTo.Count == 0)
                                {
                                    prepMsg.ReplyTo.Add(result.From.Clone());
                                }
                            }, false).ConfigureAwait(false).GetAwaiter();
                            return true; // only forward to the first valid address
                        }
                    }
                }
            }
            finally
            {
                result.Dispose();
            }
            return true;
        }
コード例 #19
0
        public async Task <IActionResult> Register(IFormFile uploadFile, RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid && model.CompanyAcceptAgreement == true)
            {
                if (uploadFile != null)
                {
                    if (Path.GetExtension(uploadFile.FileName) == ".jpg" ||
                        Path.GetExtension(uploadFile.FileName) == ".gif" ||
                        Path.GetExtension(uploadFile.FileName) == ".png")
                    {
                        string category    = DateTime.Now.Month + "-" + DateTime.Now.Year + "-CampaignImages";
                        string FilePath    = env.WebRootPath + "\\uploads\\" + category + "\\";
                        string dosyaismi   = Path.GetFileName(uploadFile.FileName);
                        var    yuklemeYeri = Path.Combine(FilePath, dosyaismi);
                        model.Logo = "uploads/" + category + "/" + dosyaismi;
                        try
                        {
                            if (!Directory.Exists(FilePath))
                            {
                                Directory.CreateDirectory(FilePath);//Eðer klasör yoksa oluþtur
                            }
                            using (var stream = new FileStream(yuklemeYeri, FileMode.Create))
                            {
                                await uploadFile.CopyToAsync(stream);
                            }

                            _context.Add(model);
                            await _context.SaveChangesAsync();

                            return(RedirectToAction("Index"));
                        }
                        catch (Exception exc) { ModelState.AddModelError("Image", "Hata: " + exc.Message); }
                    }
                    else
                    {
                        ModelState.AddModelError("Image", "Dosya uzantısı izin verilen uzantılardan olmalıdır.");
                    }
                }

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


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

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "Kullanıcı yeni bir hesap oluşturdu.");
                    var lastUser   = _context.Users.OrderByDescending(x => x.CreateDate).FirstOrDefault();
                    var newCompany = new Company {
                        Name = model.Name, Address = model.Address, Phone = model.Phone, Logo = model.Logo, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, UserId = lastUser.Id, CompanyAcceptAgreement = true
                    };
                    _context.Add(newCompany);
                    _context.SaveChanges();



                    MailSetting mailSetting2;
                    SendMessage sendMessage2;
                    mailSetting2 = _context.MailSettings.Where(a => a.Id == 1).FirstOrDefault();
                    sendMessage2 = _context.SendMessages.Where(x => x.Id == 2).FirstOrDefault();
                    string FromAddress      = mailSetting2.FromAddress;
                    string FromAddressTitle = mailSetting2.FromAddressTitle;

                    string ToAddress      = model.Email;
                    string ToAddressTitle = model.Name;
                    string Subject        = sendMessage2.Subject;
                    string BodyContent    = sendMessage2.BodyContent;

                    string SmptServer     = mailSetting2.SmptServer;
                    int    SmptPortNumber = mailSetting2.SmptPortNumber;

                    var mimeMessage = new MimeMessage();
                    mimeMessage.From.Add(new MailboxAddress(FromAddressTitle, FromAddress));
                    mimeMessage.To.Add(new MailboxAddress(ToAddressTitle, ToAddress));
                    mimeMessage.Subject = Subject;
                    mimeMessage.Body    = new TextPart("plain")
                    {
                        Text = BodyContent
                    };

                    using (var client = new SmtpClient())
                    {
                        client.Connect(SmptServer, SmptPortNumber, false);
                        client.Authenticate(mailSetting2.FromAddress, mailSetting2.FromAddressPassword);
                        client.Send(mimeMessage);
                        client.Disconnect(true);
                    }



                    return(RedirectToLocal(returnUrl));
                }



                AddErrors(result);
            }



            // If we got this far, something failed, redisplay form
            if (model.CompanyAcceptAgreement == false)
            {
                ViewBag.CompanyAcceptAgreementFalse = "Üyelik Sözleşmesi ve Gizlilik Prensiplerini Onaylamadan Üye Olamazsınız";
            }
            else
            {
                ViewBag.CompanyAcceptAgreementFalse = null;
            }

            return(View(model));
        }
コード例 #20
0
ファイル: Parser.cs プロジェクト: pengyancai/cs-util
        private static void ParseContentType(MimeMessage message)
        {
            const string headerName = "Content-Type";

              if (!message.Headers.Contains(headerName))
            return;

              var contentType = message.Headers[headerName];
              var mimeTypeString = contentType.GetValueWithoutParameter();

              if (!string.IsNullOrEmpty(mimeTypeString))
            message.MimeType = new MimeType(mimeTypeString);

              var charsetString = contentType.GetParameter("charset", true);

              if (!string.IsNullOrEmpty(charsetString))
            message.Charset = Charsets.FromString(charsetString);

              message.Boundary = contentType.GetParameter("boundary", true);
        }
コード例 #21
0
ファイル: Parser.cs プロジェクト: pengyancai/cs-util
        private static void ParseContentDisposition(MimeMessage message)
        {
            const string headerName = "Content-Disposition";

              message.Disposition = MimeMessageDisposition.None; // as default

              if (!message.Headers.Contains(headerName))
            return;

              var contentDisposition = message.Headers[headerName].GetValueWithoutParameter();

              if (string.IsNullOrEmpty(contentDisposition))
            return;

              switch (contentDisposition.ToLowerInvariant()) {
            case "inline": message.Disposition = MimeMessageDisposition.Inline; break;
            case "attachment": message.Disposition = MimeMessageDisposition.Attachment; break;
            default:
              throw new NotSupportedException(string.Format("unsupported content disposition: '{0}'", contentDisposition));
              }
        }
コード例 #22
0
ファイル: TnefPart.cs プロジェクト: richard2753/MimeKit
		static MimeMessage ExtractTnefMessage (TnefReader reader)
		{
			var builder = new BodyBuilder ();
			var message = new MimeMessage ();

			while (reader.ReadNextAttribute ()) {
				if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
					break;

				var prop = reader.TnefPropertyReader;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.RecipientTable:
					ExtractRecipientTable (reader, message);
					break;
				case TnefAttributeTag.MapiProperties:
					ExtractMapiProperties (reader, message, builder);
					break;
				case TnefAttributeTag.DateSent:
					message.Date = prop.ReadValueAsDateTime ();
					break;
				case TnefAttributeTag.Body:
					builder.TextBody = prop.ReadValueAsString ();
					break;
				}
			}

			if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
				ExtractAttachments (reader, builder);

			message.Body = builder.ToMessageBody ();

			return message;
		}
コード例 #23
0
		public void Add ( MimeMessage msg ) {
			messages.Add( msg );
		}
コード例 #24
0
        private async Task SendItemAsync(MimeMessage message, Dictionary <string, string> traceProps)
        {
            IDSSmtpClient client = null;
            string        status = "Fail";

            DateTimeOffset startTime;
            Stopwatch      timer = new Stopwatch();

            try
            {
                client = await this.clientPool.GetClient(traceProps).ConfigureAwait(false);

                startTime = DateTimeOffset.Now;
                timer.Start();
                try
                {
                    await client.SendAsync(message, traceProps).ConfigureAwait(false);
                }
                catch (ServiceNotConnectedException svcEx)
                {
                    string description = $"SmtpClient not connected: {svcEx.Source}";
                    string eventMsg    = "Closed connection, requesting new SmtpClient.";

                    this.logger.WriteException(svcEx, traceProps);
                    this.logger.TraceInformation(eventMsg, traceProps);

                    client.Refresh(traceProps);
                    await client.SendAsync(message, traceProps).ConfigureAwait(false);
                }
                catch (IOException ioex)
                {
                    string description = $"No response from MX endpoint: {ioex.Source}";
                    string eventMsg    = "Socket failure, requesting new SmtpClient.";
                    traceProps["Error Description"] = description;
                    this.logger.WriteException(ioex, traceProps);
                    this.logger.TraceInformation(eventMsg, traceProps);

                    client.Refresh(traceProps);
                    await client.SendAsync(message, traceProps).ConfigureAwait(false);
                }
                catch (SmtpCommandException ex)
                {
                    this.logger.WriteException(ex, traceProps);
                    this.logger.TraceInformation($"SmtpCommandException with message {ex.Message} has been handled ", traceProps);
                    client.Refresh(traceProps);
                    await client.SendAsync(message, traceProps).ConfigureAwait(false);
                }
                catch (SocketException ex)
                {
                    this.logger.WriteException(ex, traceProps);
                    this.logger.TraceInformation($"SocketException with message {ex.Message} has been handled ", traceProps);
                    client.Refresh(traceProps);
                    await client.SendAsync(message, traceProps).ConfigureAwait(false);
                }

                timer.Stop();
                status = "Success";
            }
            catch (SmtpProtocolException ex)
            {
                this.logger.WriteException(ex, traceProps);
                throw;
            }
            catch (SmtpCommandException ex)
            {
                string msg = string.Empty;
                switch (ex.ErrorCode)
                {
                case SmtpErrorCode.RecipientNotAccepted:
                    msg = $"Recipient not accepted: {ex.Mailbox?.Address}";
                    break;

                case SmtpErrorCode.SenderNotAccepted:
                    msg = $"Sender not accepted: {ex.Mailbox?.Address}";
                    break;

                case SmtpErrorCode.MessageNotAccepted:
                    msg = "Message not accepted.";
                    break;
                }

                traceProps["ErrorMessage"] = msg;
                this.logger.WriteException(ex, traceProps);
                throw;
            }
            catch (Exception ex)
            {
                this.logger.WriteException(ex, traceProps);
                throw;
            }
            finally
            {
                if (client != null)
                {
                    await this.clientPool.ReturnClient(client, traceProps).ConfigureAwait(false);
                }

                traceProps["Status"]   = status;
                traceProps["EndPoint"] = this.clientPool.EndPoint;
                var metrics = new Dictionary <string, double>
                {
                    { "Duration", timer.Elapsed.TotalMilliseconds },
                };
                this.logger.WriteCustomEvent("DirectSendMailService_SendMail", traceProps, metrics);

                this.logger.WriteMetric("DirectSendMailService_SendMailCount", 1, traceProps);
            }
        }
コード例 #25
0
        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <param name="emailMessage">The EmailMessage.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SendEmailAsync(EmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException(nameof(emailMessage));
            }

            string recipients = string.Join(",", emailMessage.ToAddresses.Select(r => r.Address).ToList());

            var traceProps = new Dictionary <string, string>();

            traceProps["OperationName"] = this.GetType().FullName;
            traceProps["Recipients"]    = recipients;

            var trimmedAddresses = emailMessage.ToAddresses.Where(a => !string.IsNullOrEmpty(a.Address)).ToArray();

            emailMessage.ToAddresses = trimmedAddresses;

            if (!emailMessage.ToAddresses.Any())
            {
                ArgumentNullException ex = new ArgumentNullException("ToAddresses", "Email message is missing 'To' addresses.");
                this.logger.WriteException(ex, traceProps);
                return;
            }

            var message = new MimeMessage();

            message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            if (emailMessage.CcAddresses != null && emailMessage.CcAddresses.Any())
            {
                message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            }

            message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(this.mailConfiguration.FromAddressDisplayName, x.Address)));
            message.Importance = (MimeKit.MessageImportance)emailMessage.Importance;

            message.Subject = emailMessage.Subject;

            // We will say we are sending HTML. But there are options for plaintext etc.
            if (emailMessage.FileContent != null && emailMessage.FileName != null && emailMessage.FileContent.Any() && emailMessage.FileContent.Count() == emailMessage.FileName.Count())
            {
                TextPart body = new TextPart(TextFormat.Html)
                {
                    Text = emailMessage.Content,
                };

                Multipart multipartContent = new Multipart("mixed");
                multipartContent.Add(body);

                for (var i = 0; i <= emailMessage.FileName.Count() - 1; i++)
                {
                    byte[] fileContent = Convert.FromBase64String(emailMessage.FileContent.ElementAt(i));

                    MemoryStream stream = new MemoryStream(fileContent);

                    MimePart attachment = new MimePart("text", "octet-stream")
                    {
                        Content                 = new MimeContent(stream),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(emailMessage.FileName.ElementAt(i)),
                    };
                    multipartContent.Add(attachment);
                }

                message.Body = multipartContent;
            }
            else
            {
                message.Body = new TextPart(TextFormat.Html)
                {
                    Text = emailMessage.Content,
                };
            }

            await this.SendItemAsync(message, traceProps).ConfigureAwait(false);
        }
コード例 #26
0
 /// <summary>
 /// 实例化一个电子邮件。
 /// </summary>
 /// <param name="mail">邮件实例。</param>
 /// <param name="message">电子邮件实例。</param>
 /// <returns>返回邮件实体对象。</returns>
 protected virtual Task <Multipart> InitAsync(MimeMessage mail, Email message) => Task.FromResult(default(Multipart));
コード例 #27
0
        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <param name="emailMessage">The EmailMessage.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SendMeetingInviteAsync(EmailMessage emailMessage)
        {
            if (emailMessage == null)
            {
                throw new ArgumentNullException(nameof(emailMessage));
            }

            string recipients = string.Join(",", emailMessage.ToAddresses.Select(r => r.Address).ToList());

            var traceProps = new Dictionary <string, string>();

            traceProps["OperationName"] = this.GetType().FullName;
            traceProps["Recipients"]    = recipients;

            var trimmedAddresses = emailMessage.ToAddresses.Where(a => !string.IsNullOrEmpty(a.Address)).ToArray();

            emailMessage.ToAddresses = trimmedAddresses;

            if (!emailMessage.ToAddresses.Any())
            {
                ArgumentNullException ex = new ArgumentNullException("ToAddresses", "Email message is missing 'To' addresses.");
                this.logger.WriteException(ex, traceProps);
                return;
            }

            var message = new MimeMessage();

            message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            if (emailMessage.CcAddresses != null && emailMessage.CcAddresses.Any())
            {
                message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
            }

            message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(this.mailConfiguration.FromAddressDisplayName, x.Address)));

            message.Subject    = emailMessage.Subject;
            message.Importance = (MimeKit.MessageImportance)emailMessage.Importance;

            var ical = new TextPart("calendar")
            {
                ContentTransferEncoding = ContentEncoding.Base64,
                Text = emailMessage.Content,
            };

            ical.ContentType.Parameters.Add("method", "REQUEST");

            Multipart multipart = new Multipart("mixed");

            multipart.Add(ical);

            IList <string> fileNames    = emailMessage.FileName?.ToList();
            IList <string> fileContents = emailMessage.FileContent?.ToList();
            int            i            = 0;

            if (fileNames != null && fileContents != null && fileNames.Any() && fileContents.Count == fileNames.Count)
            {
                foreach (var fileName in fileNames)
                {
                    string content = fileContents.ElementAt(i++);
                    if (!string.IsNullOrEmpty(content))
                    {
                        Stream   stream     = new MemoryStream(Convert.FromBase64String(content));
                        var      indx       = fileName.LastIndexOf('.') + 1;
                        var      fileType   = fileName.Substring(indx, fileName.Length - indx);
                        MimePart attachment = new MimePart("mixed", fileType)
                        {
                            FileName                = fileName,
                            Content                 = new MimeContent(stream, ContentEncoding.Default),
                            ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                            ContentTransferEncoding = ContentEncoding.Base64,
                        };
                        multipart.Add(attachment);
                    }
                }
            }

            message.Body = multipart;
            await this.SendItemAsync(message, traceProps).ConfigureAwait(false);
        }
コード例 #28
0
        /// <summary>
        /// 发送邮件
        /// </summary>
        public static void Send(SmtpConfig smtpConfig, MailSendingOption option)
        {
            if (smtpConfig == null)
            {
                throw new ArgumentNullException(nameof(smtpConfig));
            }

            if (string.IsNullOrWhiteSpace(smtpConfig.Server))
            {
                throw new ArgumentException("未设置SMTP Server");
            }

            if (string.IsNullOrWhiteSpace(smtpConfig.UserName))
            {
                throw new ArgumentException("未设置SMTP UserName");
            }

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

            if (string.IsNullOrWhiteSpace(option.MailTo))
            {
                throw new ArgumentException("未设置收件人");
            }

            if (string.IsNullOrWhiteSpace(option.Subject))
            {
                throw new ArgumentException("未设置邮件主题");
            }

            var from = option.From.TrimToNull() ?? smtpConfig.From.TrimToNull() ?? smtpConfig.UserName.TrimToNull() ?? throw new ArgumentNullException("未设置发件人");

            var separator = new[] { ',', ';' };

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(string.Empty, from));
            message.To.Add(new MailboxAddress(string.Empty, option.MailTo.Trim()));
            message.Subject = option.Subject;

            if (!string.IsNullOrWhiteSpace(option.CC))
            {
                var addrArr = option.CC.Split(separator, StringSplitOptions.RemoveEmptyEntries)
                              .Select(n => new MailboxAddress(string.Empty, n.Trim()));
                message.Cc.AddRange(addrArr);
            }

            if (!string.IsNullOrWhiteSpace(option.BCC))
            {
                var addrArr = option.BCC.Split(separator, StringSplitOptions.RemoveEmptyEntries)
                              .Select(n => new MailboxAddress(string.Empty, n.Trim()));
                message.Bcc.AddRange(addrArr);
            }

            if (option.AdditionalHeaders != null)
            {
            }

            if (!string.IsNullOrWhiteSpace(option.HeaderEncoding))
            {
                message.Headers.Add(HeaderId.Encoding, option.HeaderEncoding.Trim());
            }

            if (!string.IsNullOrWhiteSpace(option.Priority) &&
                Enum.TryParse(option.Priority.Trim(), out MessagePriority prri))
            {
                message.Priority = prri;
            }

            if (!string.IsNullOrWhiteSpace(option.ReplyTo))
            {
                message.ReplyTo.Add(new MailboxAddress(string.Empty, option.ReplyTo.Trim()));
            }

            var builder = new BodyBuilder();

            if (option.IsBodyHtml)
            {
                builder.HtmlBody = option.Body;
            }
            else
            {
                builder.TextBody = option.Body;
            }

            if (option.FilesToAttach != null && option.FilesToAttach.Any(n => !string.IsNullOrWhiteSpace(n)))
            {
                var attaches = option.FilesToAttach.Where(n => !string.IsNullOrWhiteSpace(n)).ToArray();

                foreach (var attach in attaches)
                {
                    builder.Attachments.Add(attach);
                }

                if (smtpConfig.ZipAttach)
                {
                    using (var zipStream = new MemoryStream())
                    {
                        using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Update))
                        {
                            foreach (var attach in attaches)
                            {
                                var fileInfo = new FileInfo(attach);
                                var entry    = archive.CreateEntry(fileInfo.Name);
                                using (var stream = entry.Open())
                                {
                                    var bytes = File.ReadAllBytes(fileInfo.FullName);
                                    stream.Write(bytes, 0, bytes.Length);
                                }
                            }
                        }
                        builder.Attachments.Add(option.Subject + ".zip", zipStream.ToArray());
                    }
                }
            }

            message.Body = builder.ToMessageBody();

            if (!string.IsNullOrWhiteSpace(option.ContentEncoding))
            {
                message.Body.Headers.Add(HeaderId.Encoding, option.ContentEncoding.Trim());
            }

            //以outlook名义发送邮件,不会被当作垃圾邮件
            message.Headers.Add("X-Priority", "3");
            message.Headers.Add("X-MSMail-Priority", "Normal");
            message.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            message.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");
            message.Headers.Add("ReturnReceipt", "1");
            if (smtpConfig.Receipt)
            {
                message.Headers.Add("Disposition-Notification-To", from);
            }
            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(smtpConfig.Server, smtpConfig.Port,
                               smtpConfig.EnableSsl ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.None);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                if (!string.IsNullOrWhiteSpace(smtpConfig.Password))
                {
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(new Credentials(smtpConfig));
                }

                client.Send(message);
                client.Disconnect(true);
            }
        }
コード例 #29
0
        public async Task SendEmailAsync(List <string> toEmailAddresses, String subject,
                                         PublicEnums.EmailTemplateList emailTemplate, Dictionary <string, PropertyMetaData> variableValues,
                                         ClaimsPrincipal user, List <string> ccEmailAddresses = null, List <EmailAttachment> attachments = null)
        {
            try
            {
                if (_emailOptions.EmailEnabled)
                {
                    var emailMessage = new MimeMessage();

                    emailMessage.From.Add(new MailboxAddress(_emailOptions.FromName, _emailOptions.FromAddress));

                    foreach (var toEmailAddress in toEmailAddresses)
                    {
                        emailMessage.To.Add(new MailboxAddress("", toEmailAddress));
                    }
                    if (ccEmailAddresses != null)
                    {
                        foreach (var ccEmailAddress in ccEmailAddresses)
                        {
                            emailMessage.Cc.Add(new MailboxAddress("", ccEmailAddress));
                        }
                    }

                    //Process email template
                    string htmlMessage = await ProcessEmailTemplate(emailTemplate, variableValues);

                    emailMessage.Subject = subject;

                    //Build body
                    var builder = new BodyBuilder();
                    builder.HtmlBody = htmlMessage;

                    //Add attachments
                    if (attachments != null && attachments.Count > 0)
                    {
                        foreach (var item in attachments)
                        {
                            builder.Attachments.Add(item.AttachmentName, item.AttachmentData, ContentType.Parse(item.ContentType));
                        }
                    }

                    emailMessage.Body = builder.ToMessageBody();

                    using (var client = new SmtpClient())
                    {
                        client.LocalDomain = _emailOptions.LocalDomain;

                        await client.ConnectAsync(_emailOptions.MailServerAddress, Convert.ToInt32(_emailOptions.MailServerPort), SecureSocketOptions.Auto).ConfigureAwait(false);

                        if (_emailOptions.RequireLogin)
                        {
                            await client.AuthenticateAsync(new NetworkCredential(_emailOptions.Username, _emailOptions.UserPassword));
                        }
                        await client.SendAsync(emailMessage).ConfigureAwait(false);

                        await client.DisconnectAsync(true).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                HelperFunctions.Log(_context, PublicEnums.LogLevel.LEVEL_EXCEPTION, "Helpers.EmailServiceFactory.EmailService.SendEmailAsync", ex.Message, user, ex);
            }
        }
コード例 #30
0
        public void SendMail(string aToEmail, string aName, GCPAdapter aAdapter)
        {
            try {
                //From Address
                string FromAddress     = "*****@*****.**";
                string FromAdressTitle = "Sender";
                //To Address
                string ToAddress     = aToEmail;
                string ToAdressTitle = "Receiver";

                string Subject     = "Tax invoice";
                string BodyContent = "This is a test sending tax invoice..";

                var body = new TextPart("plain")
                {
                    Text = BodyContent
                };
                //Smtp Server
                string SmtpServer = "smtp.gmail.com";
                //Smtp Port Number
                int SmtpPortNumber = 587;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
                mimeMessage.Subject = Subject;

                using (MemoryStream ms = new MemoryStream()) {
                    string bucketName = "apiemprevo.appspot.com";
                    aAdapter.DownloadObject(bucketName, aName, ms);

                    var attachment = new MimePart()
                    {
                        ContentObject           = new ContentObject(ms, ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = "invoice.pdf"
                    };

                    //now create the multipart/mixed container to hold the message text and the
                    //file attachment
                    var multipart = new Multipart("mixed");
                    multipart.Add(body);
                    multipart.Add(attachment);

                    // now set the multipart/mixed as the message body
                    mimeMessage.Body = multipart;

                    using (var client = new SmtpClient()) {
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                        client.Connect(SmtpServer, SmtpPortNumber, false);
                        // Note: only needed if the SMTP server requires authentication
                        // Error 5.5.1 Authentication
                        client.Authenticate(FromAddress, "Ch@mp50955");
                        client.Send(mimeMessage);
                        client.Disconnect(true);
                    }
                }
            }
            catch (Exception ex) {
                throw ex;
            }
        }
コード例 #31
0
        private void MailCheck()
        {
            DBConnect     conn          = new DBConnect();
            SqlConnection sqlConnection = new SqlConnection(@"Data Source=" + conn.host + ";Initial Catalog=" + conn.db +
                                                            ";" + "User ID=" + conn.user + ";Password="******"SELECT * FROM Mails WHERE Send_from = '{message.From.ToString().Replace("'","")}' " +
                                                 $"and Subject = '{message.Subject.ToString().Replace("'", "")}' and Send_to = '{message.To.ToString().Replace("'", "")}'";

                        bool kostyl = false;
                        using (DbDataReader reader = sqlCommand.ExecuteReader())
                        {
                            if (!reader.HasRows)
                            {
                                kostyl = true;
                            }
                        }

                        if (kostyl)
                        {
                            SqlCommand command = sqlConnection.CreateCommand();
                            command.CommandText = "INSERT INTO Mails (Send_from, Subject, Date_send, Send_to, Importance, isRead) " +
                                                  $"VALUES ('{message.From.ToString().Replace("'","")}', '{message.Subject.ToString().Replace("'", "")}', " +
                                                  $"'{message.Date.ToString().Replace("'", "")}', '{message.To.ToString().Replace("'", "")}', 'Важное', 0)";

                            command.ExecuteNonQuery();
                            inbox.AddFlags(item.UniqueId, MessageFlags.Deleted, true);
                            inbox.Expunge();
                        }
                    }

                    inbox.Close();
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Error(ex.ToString());
            }
            finally
            {
                sqlConnection.Close();
                sqlConnection.Dispose();
            }
        }
コード例 #32
0
 /// <summary>
 /// Sends the specified message.
 /// </summary>
 /// <remarks>
 /// <para>Sends the specified message.</para>
 /// <para>The sender address is determined by checking the following
 /// message headers (in order of precedence): Resent-Sender,
 /// Resent-From, Sender, and From.</para>
 /// <para>If either the Resent-Sender or Resent-From addresses are present,
 /// the recipients are collected from the Resent-To, Resent-Cc, and
 /// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para>
 /// </remarks>
 /// <example>
 /// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessage"/>
 /// </example>
 /// <param name="message">The message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="message"/> is <c>null</c>.
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public virtual void Send(MimeMessage message, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
 {
     Send(FormatOptions.Default, message, cancellationToken, progress);
 }
コード例 #33
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyTo">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bcc">BCC addresses list</param>
        /// <param name="cc">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloadId">Attachment download ID (another attachment)</param>
        /// <param name="headers">Headers</param>
        public virtual void SendEmail(EmailAccount emailAccount, string subject, string body,
                                      string fromAddress, string fromName, string toAddress, string toName,
                                      string replyTo            = null, string replyToName = null,
                                      IEnumerable <string> bcc  = null, IEnumerable <string> cc           = null,
                                      string attachmentFilePath = null, string attachmentFileName         = null,
                                      int attachedDownloadId    = 0, IDictionary <string, string> headers = null)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromAddress));
            message.To.Add(new MailboxAddress(toName, toAddress));

            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyTo.Add(new MailboxAddress(replyToName, replyTo));
            }

            //BCC
            if (bcc != null)
            {
                foreach (var address in bcc.Where(bccValue => !string.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(new MailboxAddress(address.Trim()));
                }
            }

            //CC
            if (cc != null)
            {
                foreach (var address in cc.Where(ccValue => !string.IsNullOrWhiteSpace(ccValue)))
                {
                    message.Cc.Add(new MailboxAddress(address.Trim()));
                }
            }

            //content
            message.Subject = subject;

            //headers
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    message.Headers.Add(header.Key, header.Value);
                }
            }

            var multipart = new Multipart("mixed")
            {
                new TextPart(TextFormat.Html)
                {
                    Text = body
                }
            };

            //create the file attachment for this e-mail message
            if (!string.IsNullOrEmpty(attachmentFilePath) && _fileProvider.FileExists(attachmentFilePath))
            {
                multipart.Add(CreateMimeAttachment(attachmentFilePath, attachmentFileName));
            }

            //another attachment?
            if (attachedDownloadId > 0)
            {
                var download = _downloadService.GetDownloadById(attachedDownloadId);
                //we do not support URLs as attachments
                if (!download?.UseDownloadUrl ?? false)
                {
                    multipart.Add(CreateMimeAttachment(download));
                }
            }

            message.Body = multipart;

            //send email
            using var smtpClient = _smtpBuilder.Build(emailAccount);
            smtpClient.Send(message);
            smtpClient.Disconnect(true);
        }
コード例 #34
0
        public IActionResult SenndEmail(string email)
        {
            MimeMessage message = new MimeMessage();

            MailboxAddress from = new MailboxAddress("Admin",
                                                     "*****@*****.**");

            message.From.Add(from);

            MailboxAddress to = new MailboxAddress("User",
                                                   "*****@*****.**");

            message.To.Add(to);

            message.Subject = "This is email subject";

            BodyBuilder bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = "<h1>Hello World!</h1>";
            bodyBuilder.TextBody = "Hello World!";
            message.Body         = bodyBuilder.ToMessageBody();

            MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient();
            // client.Connect("smtp.wp.pl", 465, false);
            //client.Authenticate("*****@*****.**", "KAMI21`kami");
            client.Connect("smtp.gmail.com", 465);
            client.Authenticate("kar.matgogle", "NieUrzGmail@");
            client.Send(message);
            client.Disconnect(true);
            client.Dispose();

            // Command-line argument must be the SMTP host.
            //SmtpClient client = new SmtpClient("smtp.wp.pl", 465);
            //// Specify the email sender.
            //// Create a mailing address that includes a UTF8 character
            //// in the display name.
            //MailAddress from = new MailAddress("*****@*****.**",
            //   "KAMI21`kami",
            //System.Text.Encoding.UTF8);
            //// Set destinations for the email message.
            //MailAddress to = new MailAddress("*****@*****.**");
            //// Specify the message content.
            //MailMessage message = new MailMessage(from, to);
            //message.Body = "This is a test email message sent by an application. ";
            //// Include some non-ASCII characters in body and subject.
            //string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
            //message.Body += Environment.NewLine + someArrows;
            //message.BodyEncoding = System.Text.Encoding.UTF8;
            //message.Subject = "test message 1" + someArrows;
            //message.SubjectEncoding = System.Text.Encoding.UTF8;
            //// Set the method that is called back when the send operation ends.
            //client.SendCompleted += new
            //SendCompletedEventHandler(SendCompletedCallback);
            //// The userState can be any object that allows your callback
            //// method to identify this send operation.
            //// For this example, the userToken is a string constant.
            //string userState = "test message1";
            //client.SendAsync(message, userState);
            ////Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            ////string answer = Console.ReadLine();
            //// If the user canceled the send, and mail hasn't been sent yet,
            //// then cancel the pending operation.
            ////if (answer.StartsWith("c") && mailSent == false)
            ////{
            ////    client.SendAsyncCancel();
            ////}
            //// Clean up.
            //message.Dispose();
            //Console.WriteLine("Goodbye.");

            return(RedirectToAction("index", "Home"));
        }
コード例 #35
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPassword"));
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);

                //mail

                MailSetting mailSetting3;
                SendMessage sendMessage3;
                mailSetting3 = _context.MailSettings.Where(a => a.Id == 1).FirstOrDefault();
                sendMessage3 = _context.SendMessages.Where(x => x.Id == 3).FirstOrDefault();
                string FromAddress      = mailSetting3.FromAddress;
                string FromAddressTitle = mailSetting3.FromAddressTitle;

                string ToAddress      = model.Email;
                string ToAddressTitle = model.Email;
                string Subject        = sendMessage3.Subject;
                string BodyContent    = sendMessage3.BodyContent + $"{callbackUrl}";

                string SmptServer     = mailSetting3.SmptServer;
                int    SmptPortNumber = mailSetting3.SmptPortNumber;

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(FromAddressTitle, FromAddress));
                mimeMessage.To.Add(new MailboxAddress(ToAddressTitle, ToAddress));
                mimeMessage.Subject = Subject;
                mimeMessage.Body    = new TextPart("plain")
                {
                    Text = BodyContent
                };

                using (var client = new SmtpClient())
                {
                    client.Connect(SmptServer, SmptPortNumber, false);
                    client.Authenticate(mailSetting3.FromAddress, mailSetting3.FromAddressPassword);
                    client.Send(mimeMessage);
                    client.Disconnect(true);
                }
                ViewBag.ForgotPasswordMessage = "Mailinize Şifre Sıfırlama Linki Gönderilmiştir.";

                //mail

                return(View("ForgotPassword"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #36
0
        public void Write_Binary_Test()
        {
            var bytes = Enumerable.Range(0, 256).Select(i => (byte) i).ToArray();
            var part = new MimePart(new MemoryStream(bytes));
            string result;

            using (var message = new MimeMessage(part) {Boundary = "abc123"})
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            var expected = @"--abc123
            Content-Length: 256

            " + Encoding.UTF8.GetString(bytes) + @"
            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
コード例 #37
0
ファイル: TnefPart.cs プロジェクト: richard2753/MimeKit
		static void ExtractMapiProperties (TnefReader reader, MimeMessage message, BodyBuilder builder)
		{
			var prop = reader.TnefPropertyReader;

			while (prop.ReadNextProperty ()) {
				switch (prop.PropertyTag.Id) {
				case TnefPropertyId.InternetMessageId:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
						message.MessageId = prop.ReadValueAsString ();
					}
					break;
				case TnefPropertyId.Subject:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode) {
						message.Subject = prop.ReadValueAsString ();
					}
					break;
				case TnefPropertyId.RtfCompressed:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var rtf = new TextPart ("rtf");
						rtf.ContentType.Name = "body.rtf";

						var converter = new RtfCompressedToRtf ();
						var content = new MemoryStream ();

						using (var filtered = new FilteredStream (content)) {
							filtered.Add (converter);

							using (var compressed = prop.GetRawValueReadStream ()) {
								compressed.CopyTo (filtered, 4096);
								filtered.Flush ();
							}
						}

						rtf.ContentObject = new ContentObject (content);
						content.Position = 0;

						builder.Attachments.Add (rtf);
					}
					break;
				case TnefPropertyId.BodyHtml:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var html = new TextPart ("html");
						html.ContentType.Name = "body.html";
						html.Text = prop.ReadValueAsString ();

						builder.Attachments.Add (html);
					}
					break;
				case TnefPropertyId.Body:
					if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
						prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary) {
						var plain = new TextPart ("plain");
						plain.ContentType.Name = "body.txt";
						plain.Text = prop.ReadValueAsString ();

						builder.Attachments.Add (plain);
					}
					break;
				}
			}
		}
コード例 #38
0
        public void Write_Headers_Test()
        {
            string result;
            var part = new MimePart(null)
                       {
                           ContentType = "plain/xml",
                           ContentLength = 20,
                           ContentTransferEncoding = "binary",
                           ContentDisposition = new ContentDisposition(DispositionTypeNames.Attachment)
                       };

            var message = new MimeMessage(part) {Boundary = "abc123"};

            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            const string expected = @"--abc123
            Content-Type: plain/xml
            Content-Length: 20
            Content-Transfer-Encoding: binary
            Content-Disposition: attachment

            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
コード例 #39
0
        public override void RunCommand(object sender)
        {
            var         engine                 = (AutomationEngineInstance)sender;
            MimeMessage vMimeMessage           = (MimeMessage)v_IMAPMimeMessage.ConvertUserVariableToObject(engine);
            string      vIMAPHost              = v_IMAPHost.ConvertUserVariableToString(engine);
            string      vIMAPPort              = v_IMAPPort.ConvertUserVariableToString(engine);
            string      vIMAPUserName          = v_IMAPUserName.ConvertUserVariableToString(engine);
            string      vIMAPPassword          = v_IMAPPassword.ConvertUserVariableToString(engine);
            var         vIMAPDestinationFolder = v_IMAPDestinationFolder.ConvertUserVariableToString(engine);

            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (sndr, certificate, chain, sslPolicyErrors) => true;
                client.SslProtocols = SslProtocols.None;

                using (var cancel = new CancellationTokenSource())
                {
                    try
                    {
                        client.Connect(v_IMAPHost, int.Parse(v_IMAPPort), true, cancel.Token);                         //SSL
                    }
                    catch (Exception)
                    {
                        client.Connect(v_IMAPHost, int.Parse(v_IMAPPort));                         //TLS
                    }

                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(vIMAPUserName, vIMAPPassword, cancel.Token);

                    var      splitId   = vMimeMessage.MessageId.Split('#').ToList();
                    UniqueId messageId = UniqueId.Parse(splitId.Last());
                    splitId.RemoveAt(splitId.Count - 1);
                    string messageFolder = string.Join("", splitId);

                    IMailFolder toplevel               = client.GetFolder(client.PersonalNamespaces[0]);
                    IMailFolder foundSourceFolder      = GetIMAPEmailsCommand.FindFolder(toplevel, messageFolder);
                    IMailFolder foundDestinationFolder = GetIMAPEmailsCommand.FindFolder(toplevel, vIMAPDestinationFolder);

                    if (foundSourceFolder != null)
                    {
                        foundSourceFolder.Open(FolderAccess.ReadWrite, cancel.Token);
                    }
                    else
                    {
                        throw new Exception("Source Folder not found");
                    }

                    if (foundDestinationFolder == null)
                    {
                        throw new Exception("Destination Folder not found");
                    }

                    var messageSummary = foundSourceFolder.Fetch(new[] { messageId }, MessageSummaryItems.Flags);

                    if (v_IMAPOperationType == "Move MimeMessage")
                    {
                        if (v_IMAPMoveCopyUnreadOnly == "Yes")
                        {
                            if (!messageSummary[0].Flags.Value.HasFlag(MessageFlags.Seen))
                            {
                                foundSourceFolder.MoveTo(messageId, foundDestinationFolder, cancel.Token);
                            }
                        }
                        else
                        {
                            foundSourceFolder.MoveTo(messageId, foundDestinationFolder, cancel.Token);
                        }
                    }
                    else if (v_IMAPOperationType == "Copy MimeMessage")
                    {
                        if (v_IMAPMoveCopyUnreadOnly == "Yes")
                        {
                            if (!messageSummary[0].Flags.Value.HasFlag(MessageFlags.Seen))
                            {
                                foundSourceFolder.CopyTo(messageId, foundDestinationFolder, cancel.Token);
                            }
                        }
                        else
                        {
                            foundSourceFolder.CopyTo(messageId, foundDestinationFolder, cancel.Token);
                        }
                    }

                    client.Disconnect(true, cancel.Token);
                    client.ServerCertificateValidationCallback = null;
                }
            }
        }
コード例 #40
0
ファイル: TnefTests.cs プロジェクト: tablesmit/MimeKit
        static MimeMessage ExtractTnefMessage(TnefReader reader)
        {
            var builder = new BodyBuilder();
            var message = new MimeMessage();

            while (reader.ReadNextAttribute())
            {
                if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
                {
                    break;
                }

                if (reader.AttributeLevel != TnefAttributeLevel.Message)
                {
                    Assert.Fail("Unknown attribute level: {0}", reader.AttributeLevel);
                }

                var prop = reader.TnefPropertyReader;

                switch (reader.AttributeTag)
                {
                case TnefAttributeTag.RecipientTable:
                    ExtractRecipientTable(reader, message);
                    break;

                case TnefAttributeTag.MapiProperties:
                    ExtractMapiProperties(reader, message, builder);
                    break;

                case TnefAttributeTag.DateSent:
                    message.Date = prop.ReadValueAsDateTime();
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, message.Date);
                    break;

                case TnefAttributeTag.Body:
                    builder.TextBody = prop.ReadValueAsString();
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, builder.TextBody);
                    break;

                case TnefAttributeTag.TnefVersion:
                    Console.WriteLine("Message Attribute: {0} = {1}", reader.AttributeTag, prop.ReadValueAsInt32());
                    break;

                case TnefAttributeTag.OemCodepage:
                    int codepage = prop.ReadValueAsInt32();
                    try {
                        var encoding = Encoding.GetEncoding(codepage);
                        Console.WriteLine("Message Attribute: OemCodepage = {0}", encoding.HeaderName);
                    }
                    catch {
                        Console.WriteLine("Message Attribute: OemCodepage = {0}", codepage);
                    }
                    break;

                default:
                    Console.WriteLine("Message Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue());
                    break;
                }
            }

            if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
            {
                ExtractAttachments(reader, builder);
            }
            else
            {
                Console.WriteLine("no attachments");
            }

            message.Body = builder.ToMessageBody();

            return(message);
        }
コード例 #41
0
ファイル: Parser.cs プロジェクト: pengyancai/cs-util
        private static void ParseContentTransferEncoding(MimeMessage message)
        {
            message.TransferEncoding = ContentTransferEncodingMethod.SevenBit; // as default

              if (!message.Headers.Contains(ContentTransferEncoding.HeaderName))
            return;

              var contentTransferEncoding = message.Headers[ContentTransferEncoding.HeaderName].GetValueWithoutParameter();

              if (string.IsNullOrEmpty(contentTransferEncoding))
            return;

              message.TransferEncoding = ContentTransferEncoding.GetEncodingMethod(contentTransferEncoding);
        }
コード例 #42
0
ファイル: TnefTests.cs プロジェクト: tablesmit/MimeKit
        static void ExtractMapiProperties(TnefReader reader, MimeMessage message, BodyBuilder builder)
        {
            var prop = reader.TnefPropertyReader;

            while (prop.ReadNextProperty())
            {
                switch (prop.PropertyTag.Id)
                {
                case TnefPropertyId.InternetMessageId:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.MessageId = prop.ReadValueAsString();
                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, message.MessageId);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for Message-Id: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.Subject:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode)
                    {
                        message.Subject = prop.ReadValueAsString();
                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, message.Subject);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for Subject: {0}", prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.RtfCompressed:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var rtf = new TextPart("rtf");
                        rtf.ContentType.Name = "body.rtf";

                        var converter = new RtfCompressedToRtf();
                        var content   = new MemoryStream();

                        using (var filtered = new FilteredStream(content)) {
                            filtered.Add(converter);

                            using (var compressed = prop.GetRawValueReadStream()) {
                                compressed.CopyTo(filtered, 4096);
                                filtered.Flush();
                            }
                        }

                        rtf.ContentObject = new ContentObject(content);
                        content.Position  = 0;

                        builder.Attachments.Add(rtf);

                        Console.WriteLine("Message Property: {0} = <compressed rtf data>", prop.PropertyTag.Id);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.BodyHtml:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var html = new TextPart("html");
                        html.ContentType.Name = "body.html";
                        html.Text             = prop.ReadValueAsString();

                        builder.Attachments.Add(html);

                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, html.Text);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                case TnefPropertyId.Body:
                    if (prop.PropertyTag.ValueTnefType == TnefPropertyType.String8 ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Unicode ||
                        prop.PropertyTag.ValueTnefType == TnefPropertyType.Binary)
                    {
                        var plain = new TextPart("plain");
                        plain.ContentType.Name = "body.txt";
                        plain.Text             = prop.ReadValueAsString();

                        builder.Attachments.Add(plain);

                        Console.WriteLine("Message Property: {0} = {1}", prop.PropertyTag.Id, plain.Text);
                    }
                    else
                    {
                        Assert.Fail("Unknown property type for {0}: {1}", prop.PropertyTag.Id, prop.PropertyTag.ValueTnefType);
                    }
                    break;

                default:
                    object value;

                    try {
                        value = prop.ReadValue();
                    } catch {
                        value = null;
                    }

                    Console.WriteLine("Message Property (unhandled): {0} = {1}", prop.PropertyTag.Id, value);
                    break;
                }
            }
        }
コード例 #43
0
ファイル: Parser.cs プロジェクト: pengyancai/cs-util
        private static MimeMessage ParseBody(LineOrientedStream stream, MimeHeaderCollection headers)
        {
            var message = new MimeMessage(headers);

              ParseContentType(message);
              ParseContentTransferEncoding(message);
              ParseContentDisposition(message);

              // read and parse content
              MemoryStream contentStream;

              if (message.MimeType == null || !message.MimeType.TypeEquals("multipart")) {
            contentStream = new MemoryStream(1024);

            stream.CopyTo(contentStream, MimeFormat.Standard.Folding);

            message.Content = contentStream;

            return message;
              }

              // multipart/*
              var parts = new List<MimeMessage>();
              var delimiter = new ByteString("--" + message.Boundary);
              var closeDelimiter = new ByteString("--" + message.Boundary + "--");
              MemoryStream body = null;
              ByteString line = null;
              ByteString lastLine = null;

              contentStream = new MemoryStream(1024);

              for (;;) {
            if (lastLine != null)
              contentStream.Write(lastLine.ByteArray, 0, lastLine.Length);

            var l = stream.ReadLine();

            if (l == null)
              break;

            lastLine = line;
            line = new ByteString(l);

            if (line.StartsWith(delimiter)) {
              if (lastLine != null) {
            if (lastLine.EndsWith(Octets.CRLF))
              // CRLF "--" boundary
              contentStream.Write(lastLine.ByteArray, 0, lastLine.Length - 2);
            else
              // LF "--" boundary or CR "--" boundary
              contentStream.Write(lastLine.ByteArray, 0, lastLine.Length - 1);
              }

              contentStream.Position = 0;

              if (body == null)
            body = contentStream;
              else
            parts.Add(Parse(contentStream));

              if (line.StartsWith(closeDelimiter))
            break;
              else
            contentStream = new MemoryStream(1024);

              lastLine = null;
            }
              }

              message.Content = body;
              message.SubParts.AddRange(parts);

              return message;
        }
コード例 #44
0
        internal static ArcSignatureValidationResult GetArcHeaderSets(MimeMessage message, bool throwOnError, out ArcHeaderSet[] sets, out int count)
        {
            ArcHeaderSet set;

            sets  = new ArcHeaderSet[50];
            count = 0;

            for (int i = 0; i < message.Headers.Count; i++)
            {
                Dictionary <string, string> parameters = null;
                var    header = message.Headers[i];
                int    instance;
                string value;

                switch (header.Id)
                {
                case HeaderId.ArcAuthenticationResults:
                    if (!AuthenticationResults.TryParse(header.RawValue, out AuthenticationResults authres))
                    {
                        if (throwOnError)
                        {
                            throw new FormatException("Invalid ARC-Authentication-Results header.");
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }

                    if (!authres.Instance.HasValue)
                    {
                        if (throwOnError)
                        {
                            throw new FormatException("Missing instance tag in ARC-Authentication-Results header.");
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }

                    instance = authres.Instance.Value;

                    if (instance < 1 || instance > 50)
                    {
                        if (throwOnError)
                        {
                            throw new FormatException(string.Format("Invalid instance tag in ARC-Authentication-Results header: i={0}", instance));
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }
                    break;

                case HeaderId.ArcMessageSignature:
                case HeaderId.ArcSeal:
                    try {
                        parameters = ParseParameterTags(header.Id, header.Value);
                    } catch {
                        if (throwOnError)
                        {
                            throw;
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }

                    if (!parameters.TryGetValue("i", out value))
                    {
                        if (throwOnError)
                        {
                            throw new FormatException(string.Format("Missing instance tag in {0} header.", header.Id.ToHeaderName()));
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }

                    if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out instance) || instance < 1 || instance > 50)
                    {
                        if (throwOnError)
                        {
                            throw new FormatException(string.Format("Invalid instance tag in {0} header: i={1}", header.Id.ToHeaderName(), value));
                        }

                        return(ArcSignatureValidationResult.Fail);
                    }
                    break;

                default:
                    instance = 0;
                    break;
                }

                if (instance == 0)
                {
                    continue;
                }

                set = sets[instance - 1];
                if (set == null)
                {
                    sets[instance - 1] = set = new ArcHeaderSet();
                }

                if (!set.Add(header, parameters))
                {
                    return(ArcSignatureValidationResult.Fail);
                }

                if (instance > count)
                {
                    count = instance;
                }
            }

            if (count == 0)
            {
                // there are no ARC sets
                return(ArcSignatureValidationResult.None);
            }

            // verify that all ARC sets are complete
            for (int i = 0; i < count; i++)
            {
                set = sets[i];

                if (set == null)
                {
                    if (throwOnError)
                    {
                        throw new FormatException(string.Format("Missing ARC headers for i={0}", i + 1));
                    }

                    return(ArcSignatureValidationResult.Fail);
                }

                if (set.ArcAuthenticationResult == null)
                {
                    if (throwOnError)
                    {
                        throw new FormatException(string.Format("Missing ARC-Authentication-Results header for i={0}", i + 1));
                    }

                    return(ArcSignatureValidationResult.Fail);
                }

                if (set.ArcMessageSignature == null)
                {
                    if (throwOnError)
                    {
                        throw new FormatException(string.Format("Missing ARC-Message-Signature header for i={0}", i + 1));
                    }

                    return(ArcSignatureValidationResult.Fail);
                }

                if (set.ArcSeal == null)
                {
                    if (throwOnError)
                    {
                        throw new FormatException(string.Format("Missing ARC-Seal header for i={0}", i + 1));
                    }

                    return(ArcSignatureValidationResult.Fail);
                }

                if (!set.ArcSealParameters.TryGetValue("cv", out string cv))
                {
                    if (throwOnError)
                    {
                        throw new FormatException(string.Format("Missing chain validation tag in ARC-Seal header for i={0}.", i + 1));
                    }

                    return(ArcSignatureValidationResult.Fail);
                }

                // The "cv" value for all ARC-Seal header fields MUST NOT be
                // "fail". For ARC Sets with instance values > 1, the values
                // MUST be "pass". For the ARC Set with instance value = 1, the
                // value MUST be "none".
                if (!cv.Equals(i == 0 ? "none" : "pass", StringComparison.Ordinal))
                {
                    return(ArcSignatureValidationResult.Fail);
                }
            }

            return(ArcSignatureValidationResult.Pass);
        }
コード例 #45
0
        async Task <bool> VerifyArcMessageSignatureAsync(FormatOptions options, MimeMessage message, Header arcSignature, Dictionary <string, string> parameters, bool doAsync, CancellationToken cancellationToken)
        {
            DkimCanonicalizationAlgorithm headerAlgorithm, bodyAlgorithm;
            DkimSignatureAlgorithm        signatureAlgorithm;
            AsymmetricKeyParameter        key;
            string d, s, q, bh, b;

            string[] headers;
            int      maxLength;

            ValidateArcMessageSignatureParameters(parameters, out signatureAlgorithm, out headerAlgorithm, out bodyAlgorithm,
                                                  out d, out s, out q, out headers, out bh, out b, out maxLength);

            if (!IsEnabled(signatureAlgorithm))
            {
                return(false);
            }

            if (doAsync)
            {
                key = await PublicKeyLocator.LocatePublicKeyAsync(q, d, s, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                key = PublicKeyLocator.LocatePublicKey(q, d, s, cancellationToken);
            }

            if ((key is RsaKeyParameters rsa) && rsa.Modulus.BitLength < MinimumRsaKeyLength)
            {
                return(false);
            }

            options = options.Clone();
            options.NewLineFormat = NewLineFormat.Dos;

            // first check the body hash (if that's invalid, then the entire signature is invalid)
            var hash = Convert.ToBase64String(message.HashBody(options, signatureAlgorithm, bodyAlgorithm, maxLength));

            if (hash != bh)
            {
                return(false);
            }

            using (var stream = new DkimSignatureStream(CreateVerifyContext(signatureAlgorithm, key))) {
                using (var filtered = new FilteredStream(stream)) {
                    filtered.Add(options.CreateNewLineFilter());

                    WriteHeaders(options, message, headers, headerAlgorithm, filtered);

                    // now include the ARC-Message-Signature header that we are verifying,
                    // but only after removing the "b=" signature value.
                    var header = GetSignedSignatureHeader(arcSignature);

                    switch (headerAlgorithm)
                    {
                    case DkimCanonicalizationAlgorithm.Relaxed:
                        WriteHeaderRelaxed(options, filtered, header, true);
                        break;

                    default:
                        WriteHeaderSimple(options, filtered, header, true);
                        break;
                    }

                    filtered.Flush();
                }

                return(stream.VerifySignature(b));
            }
        }
コード例 #46
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                SetProgress(20, "Create mime message");

                var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);

                var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);

                var mimeMessage = new MimeMessage
                {
                    Subject = messageSubject
                };

                mimeMessage.From.Add(fromAddress);

                mimeMessage.To.Add(toAddress);

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = messageBody
                };

                mimeMessage.Body = bodyBuilder.ToMessageBody();

                mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");

                using (var client = GetSmtpClient())
                {
                    SetProgress(40, "Connect to host");

                    client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
                                   SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);

                    if (SmtpSettings.EnableAuth)
                    {
                        SetProgress(60, "Authenticate");

                        client.Authenticate(SmtpSettings.CredentialsUserName,
                                            SmtpSettings.CredentialsUserPassword, cancellationToken);
                    }

                    SetProgress(80, "Send test message");

                    client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
                }
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (SocketException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (AuthenticationException ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            catch (Exception ex)
            {
                Error = ex.Message; //TODO: Add translates of ordinary cases
                Logger.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();

                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
コード例 #47
0
ファイル: TnefTests.cs プロジェクト: tablesmit/MimeKit
        static void ExtractRecipientTable(TnefReader reader, MimeMessage message)
        {
            var prop = reader.TnefPropertyReader;

            // Note: The RecipientTable uses rows of properties...
            while (prop.ReadNextRow())
            {
                InternetAddressList list = null;
                string name = null, addr = null;

                while (prop.ReadNextProperty())
                {
                    switch (prop.PropertyTag.Id)
                    {
                    case TnefPropertyId.RecipientType:
                        int recipientType = prop.ReadValueAsInt32();
                        switch (recipientType)
                        {
                        case 1: list = message.To; break;

                        case 2: list = message.Cc; break;

                        case 3: list = message.Bcc; break;

                        default:
                            Assert.Fail("Invalid recipient type.");
                            break;
                        }
                        Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, recipientType);
                        break;

                    case TnefPropertyId.TransmitableDisplayName:
                        if (string.IsNullOrEmpty(name))
                        {
                            name = prop.ReadValueAsString();
                            Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        }
                        else
                        {
                            Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString());
                        }
                        break;

                    case TnefPropertyId.DisplayName:
                        name = prop.ReadValueAsString();
                        Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        break;

                    case TnefPropertyId.EmailAddress:
                        if (string.IsNullOrEmpty(addr))
                        {
                            addr = prop.ReadValueAsString();
                            Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        }
                        else
                        {
                            Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString());
                        }
                        break;

                    case TnefPropertyId.SmtpAddress:
                        // The SmtpAddress, if it exists, should take precedence over the EmailAddress
                        // (since the SmtpAddress is meant to be used in the RCPT TO command).
                        addr = prop.ReadValueAsString();
                        Console.WriteLine("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        break;

                    default:
                        Console.WriteLine("RecipientTable Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue());
                        break;
                    }
                }

                Assert.IsNotNull(list, "The recipient type was never specified.");
                Assert.IsNotNull(addr, "The address was never specified.");

                if (list != null)
                {
                    list.Add(new MailboxAddress(name, addr));
                }
            }
        }
コード例 #48
0
ファイル: MimeMessageCreator.cs プロジェクト: jbautistam/Pop3
        /// <summary>
        ///		Obtiene la cadena con el cuerpo del mensaje
        /// </summary>
        private static string GetReadableMessageBody(MimeMessage objMessage, string strCharSet)
        {
            StringBuilder sb = new StringBuilder();

                // Añade el cuerpo del mensaje
                    if (string.IsNullOrEmpty(objMessage.BodyHTML.Content))
                        sb.Append(GetTextMessageBody(objMessage.Body.Content, "text/plain", strCharSet));
                    else if (string.IsNullOrEmpty(objMessage.Body.Content))
                        sb.Append(GetTextMessageBody(objMessage.BodyHTML.Content, "text/html", strCharSet));
                    else
                        sb.Append(GetAltMessageBody(GetTextMessageBody(objMessage.Body.Content, "text/plain", strCharSet),
                                                    GetTextMessageBody(objMessage.BodyHTML.Content, "text/html", strCharSet)));
                // Devuelve la cadena
                    return sb.ToString().Trim();
        }
コード例 #49
0
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
            {
                return;
            }

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            ParsedResultType level;

            if (result is Exception)
            {
                level = ParsedResultType.Fatal;
            }
            else if (result != null && result is Library.Interface.IBasicResults)
            {
                level = ((IBasicResults)result).ParsedResult;
            }
            else
            {
                level = ParsedResultType.Error;
            }

            m_parsedresultlevel = level.ToString();

            if (string.Equals(m_operationname, "Backup", StringComparison.OrdinalIgnoreCase))
            {
                if (!m_levels.Any(x => string.Equals(x, "all", StringComparison.OrdinalIgnoreCase)))
                {
                    //Check if this level should send mail
                    if (!m_levels.Any(x => string.Equals(x, level.ToString(), StringComparison.OrdinalIgnoreCase)))
                    {
                        return;
                    }
                }
            }

            try
            {
                string body    = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.Path.IsPathRooted(body) && System.IO.File.Exists(body))
                {
                    body = System.IO.File.ReadAllText(body);
                }

                body    = ReplaceTemplate(body, result, false);
                subject = ReplaceTemplate(subject, result, true);

                var            message = new MimeMessage();
                MailboxAddress mailbox;
                foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox))
                    {
                        message.To.Add(mailbox);
                    }
                }

                var    mailboxToFirst = (MailboxAddress)message.To.First();
                string toMailDomain   = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@", StringComparison.Ordinal) + 1);

                string from = m_from.Trim().Replace("\"", "");
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">", StringComparison.Ordinal))
                    {
                        from = from.Insert(from.Length - 1, "@" + toMailDomain);
                    }
                    else
                    {
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain);
                    }
                }

                if (MailboxAddress.TryParse(from, out mailbox))
                {
                    message.From.Add(mailbox);
                }

                message.Subject = subject;
                message.Body    = new TextPart("plain")
                {
                    Text = body, ContentTransferEncoding = ContentEncoding.EightBit
                };

                List <string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List <string>();

                    //Grab all IPv4 addresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                    {
                        try
                        {
                            foreach (IPAddress dnsAddress in networkInterface.GetIPProperties().DnsAddresses)
                            {
                                if (dnsAddress.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    dnslist.Add(dnsAddress.ToString());
                                }
                            }
                        }
                        catch { }
                    }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var records = new List <MXRecord>();
                    foreach (var s in dnslist)
                    {
                        var res = dnslite.getMXRecords(toMailDomain, s);
                        if (res != null)
                        {
                            records.AddRange(res.OfType <MXRecord>());
                        }
                    }

                    servers = records.OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                    {
                        throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                    }
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                               let srv = (n == null || n.IndexOf("://", StringComparison.OrdinalIgnoreCase) > 0) ? n : "smtp://" + n
                                         where !string.IsNullOrEmpty(srv)
                                         select srv).Distinct().ToList();
                }

                Exception lastEx     = null;
                string    lastServer = null;

                foreach (var server in servers)
                {
                    if (lastEx != null)
                    {
                        Logging.Log.WriteWarningMessage(LOGTAG, "SendMailFailedWillRetry", lastEx, Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server));
                    }

                    lastServer = server;
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            try
                            {
                                using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms)))
                                {
                                    client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                                    // Backward compatibility fix for setup prior to using MailKit
                                    var uri = new System.Uri(server);
                                    if (uri.Scheme.ToLowerInvariant() == "tls")
                                    {
                                        uri = new System.Uri("smtp://" + uri.Host + ":" + (uri.Port <= 0 ? 587 : uri.Port) + "/?starttls=always");
                                    }

                                    client.Connect(uri);

                                    if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                                    {
                                        client.Authenticate(m_username, m_password);
                                    }

                                    client.Send(message);
                                    client.Disconnect(true);
                                }
                            }
                            finally
                            {
                                var log = Encoding.UTF8.GetString(ms.GetBuffer());
                                if (!string.IsNullOrWhiteSpace(log))
                                {
                                    Logging.Log.WriteProfilingMessage(LOGTAG, "SendMailResult", Strings.SendMail.SendMailLog(log));
                                }
                            }
                        }

                        lastEx = null;
                        Logging.Log.WriteInformationMessage(LOGTAG, "SendMailComplete", Strings.SendMail.SendMailSuccess(server));
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                {
                    throw lastEx;
                }
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var       sb  = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                    {
                        sb.Append("--> ");
                    }
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteWarningMessage(LOGTAG, "SendMailError", ex, Strings.SendMail.SendMailFailedError(sb.ToString()));
            }
        }
コード例 #50
0
        /// <summary>
        /// Sendsmtps the mail.
        /// </summary>
        /// <returns>The mail.</returns>
        /// <param name="texter">Texter.</param>
        /// <param name="header">Header.</param>
        /// <param name="image">Image.</param>
        /// <param name="hotelCode">Hotel code.</param>
        /// <param name="resNo">Res no.</param>
        public static async Task <bool> SendsmtpMail(string texter, string header, byte[] image, string hotelCode, string resNo)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Cinnamon Guest Feedback App", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Thimira", "*****@*****.**"));
                message.Subject = "CGFS APP";

                //message.Body = new TextPart(TextFormat.Html)
                //{
                //    Text = "<html>" +
                //            "<h1>Cinnamon Guest Feedback App</h1>" +
                //            "<h2>" + header + "</h2>" +
                //            "<p>" + texter + "</p>" +
                //            "</html>"
                //};

                // create our message text, just like before (except don't set it as the message.Body)
                var body = new TextPart(TextFormat.Html)
                {
                    Text = "<html>" +
                           "<h1>Cinnamon Guest Feedback App</h1>" +
                           "<h2>" + header + "</h2>" +
                           "<p>" + texter + "</p>" +
                           "</html>"
                };

                MemoryStream memoryStream = new MemoryStream(image);

                // create an image attachment for the file located at path
                var attachment = new MimePart("image", "jpg")
                {
                    Content                 = new MimeContent(memoryStream, ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName                = $"{hotelCode}_{resNo}.jpg"
                };

                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);

                // now set the multipart/mixed as the message body
                message.Body = multipart;


                using (var client = new SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await client.ConnectAsync("smtp.office365.com", 587, false);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    await client.AuthenticateAsync("*****@*****.**", Settings.SMTPPassword);

                    await client.SendAsync(message);

                    Console.WriteLine("E mail Sent");

                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #51
0
 /// <summary>
 /// Sends the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Sends the specified message using the supplied sender and recipients.
 /// </remarks>
 /// <param name="message">The message.</param>
 /// <param name="sender">The mailbox address to use for sending the message.</param>
 /// <param name="recipients">The mailbox addresses that should receive the message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="sender"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="recipients"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public virtual void Send(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
 {
     Send(FormatOptions.Default, message, sender, recipients, cancellationToken, progress);
 }
コード例 #52
0
        public async Task SendEmailAsync(EmailMessage emailMessage)
        {
            try
            {
                var message = new MimeMessage();
                if (emailMessage.ToAddresses.Any())
                {
                    message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }
                else
                {
                    throw new InvalidOperationException("Can't Send messages without any destination address");
                }

                if (emailMessage.CcAddresses.Any())
                {
                    message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }
                if (emailMessage.BccAddresses.Any())
                {
                    message.Bcc.AddRange(emailMessage.BccAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }

                if (emailMessage.BccAddresses.Any())
                {
                    message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                }
                else
                {
                    message.From.Add(new MailboxAddress(_emailConfiguration.DefaultEmailName, _emailConfiguration.DefaultEmailAddress));
                }
                message.Subject = emailMessage.Subject;
                //We will say we are sending HTML. But there are options for plaintext etc.
                message.Body = new TextPart(TextFormat.Html)
                {
                    Text = emailMessage.Content
                };

                //Be careful that the SmtpClient class is the one from Mailkit not the framework!
                using (var emailClient = new SmtpClient())
                {
                    emailClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    //The last parameter here is to use SSL (Which you should!)
                    await emailClient.ConnectAsync(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, true);

                    //Remove any OAuth functionality as we won't be using it.
                    emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                    await emailClient.AuthenticateAsync(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);

                    await emailClient.SendAsync(message);

                    await emailClient.DisconnectAsync(true);
                }
            }

            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
            }
        }
コード例 #53
0
 /// <summary>
 /// Sends the specified message.
 /// </summary>
 /// <remarks>
 /// <para>Sends the specified message.</para>
 /// <para>The sender address is determined by checking the following
 /// message headers (in order of precedence): Resent-Sender,
 /// Resent-From, Sender, and From.</para>
 /// <para>If either the Resent-Sender or Resent-From addresses are present,
 /// the recipients are collected from the Resent-To, Resent-Cc, and
 /// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para>
 /// </remarks>
 /// <example>
 /// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessageWithOptions"/>
 /// </example>
 /// <param name="options">The formatting options.</param>
 /// <param name="message">The message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="options"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public abstract void Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
コード例 #54
0
 /// <summary>
 /// Sends the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Sends the specified message using the supplied sender and recipients.
 /// </remarks>
 /// <param name="options">The formatting options.</param>
 /// <param name="message">The message.</param>
 /// <param name="sender">The mailbox address to use for sending the message.</param>
 /// <param name="recipients">The mailbox addresses that should receive the message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="options"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="sender"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="recipients"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public abstract void Send(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
コード例 #55
0
        public void Write_Empty_Test()
        {
            var message = new MimeMessage {Boundary = "abc123"};
            string result;

            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            Assert.That(result, Is.EqualTo("--abc123--"));
        }
コード例 #56
0
 public TaxiMessage(MimeMessage message)
 {
     Date        = message.Date;
     _bodyHtml   = message.HtmlBody;
     _rootObject = LoadTaxiData(_bodyHtml);
 }
コード例 #57
0
        public void Write_Single_Plain_Text_Test()
        {
            var part = new MimePart(new MemoryStream(Encoding.UTF8.GetBytes("plain text")));
            string result;

            using (var message = new MimeMessage(part) {Boundary = "abc123"})
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                message.WriteTo(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = reader.ReadToEnd();
            }

            const string expected = @"--abc123
            Content-Length: 10

            plain text
            --abc123--";
            Assert.That(result, Is.EqualTo(expected));
        }
コード例 #58
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            string password = GeneratePassword();

            var pubpriKeys = Encryption.GenerateAsymmetricKeys();

            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, Address = Input.Address, PrivateKey = pubpriKeys.PrivateKey, PublicKey = pubpriKeys.PublicKey
                };
                var result = await _userManager.CreateAsync(user, password);

                var ip = HttpContext.Connection.RemoteIpAddress;
                if (result.Succeeded)
                {
                    _logger.LogInformation("-->" + User.Identity.Name + " has successfully created a new account with a password from this Ip address " + ip);


                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    //StudentTeacher table
                    data.teacherEmail = User.Identity.Name;
                    data.studentEmail = Input.Email;
                    _studentTeacherService.AddMember(data);

                    /*
                     * await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                     *  $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
                     */

                    // Send email to new user
                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress("Account Information", "*****@*****.**"));
                    message.To.Add(new MailboxAddress("New Account", Input.Email));
                    message.Subject = "Your new school account is set up!";
                    message.Body    = new TextPart("plain")
                    {
                        Text = "Your school information\n\n" +
                               "Full name: " + Input.FirstName + " " + Input.LastName + "\n" +
                               "Address: " + Input.Address + "\n" +
                               "Password: "******"\n\nDO NOT SHARE YOUR PASSWORD"
                    };
                    using (var client = new SmtpClient())
                    {
                        client.Connect("smtp.gmail.com", 587, false);
                        client.Authenticate("*****@*****.**", "visualstudio");
                        client.Send(message);
                        client.Disconnect(true);
                    }


                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        //Do not sign in the newly created user
                        //await _signInManager.SignInAsync(user, isPersistent: false);
                        return(LocalRedirect(returnUrl));
                    }
                }

                _logger.LogError("-->" + User.Identity.Name + " could not create an account from this Ip address " + ip);

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
コード例 #59
0
        private WebRequest CreateRequest(string uri, RequestOperation op)
        {
            var request = WebRequest.Create(uri);
            request.Method = op.Method.ToString().ToUpper();
            request.Timeout = Timeout;
            request.PreAuthenticate = true;

            if (_proxySet)
            {
                request.Proxy = _proxy;
            }

            var httpRequest = request as HttpWebRequest;
            if (httpRequest != null)
            {
                httpRequest.AllowAutoRedirect = false;
                httpRequest.ReadWriteTimeout = Timeout;
                httpRequest.KeepAlive = false;
                httpRequest.ProtocolVersion = HttpVersion.Version10;

                if (Accept != null)
                {
                    httpRequest.Accept = string.Join(",", Array.ConvertAll(Accept, type => MediaTypeNames.GetMediaType(type)));
                }

                if (Cookies != null)
                {
                    httpRequest.CookieContainer = Cookies;
                }

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    httpRequest.UserAgent = UserAgent;
                }
            }

            if (Credentials != null)
            {
                request.Credentials = Credentials;
            }
            else if (!string.IsNullOrEmpty(UserName) || !string.IsNullOrEmpty(Password))
            {
                var uriPrefix = new Uri(uri);
                var cred = new NetworkCredential(UserName, Password);
                request.Credentials = new CredentialCache
                                      {
                                          {uriPrefix, "Basic", cred},
                                          {uriPrefix, "Digest", cred},
                                          {uriPrefix, "NTLM", cred},
                                          {uriPrefix, "Kerberos", cred},
                                          {uriPrefix, "Negotiate", cred}
                                      };
            }
            else
            {
                request.Credentials = CredentialCache.DefaultCredentials;
            }

            if (!string.IsNullOrEmpty(op.ETag))
            {
                var header = op.Method == HttpMethod.Get
                                 ? HttpRequestHeader.IfNoneMatch
                                 : HttpRequestHeader.IfMatch;
                request.Headers[header] = op.ETag;
            }

            if (op.Resource != null)
            {
                using (var stream = request.GetRequestStream())
                {
                    var requestStream = op.Files.Count > 0 ? new MemoryStream() : stream;
                    MediaType mediaType;

                    if (op.Resource is ISyndicationResource)
                    {
                        mediaType = op.Resource is AtomFeed ? MediaType.Atom : MediaType.AtomEntry;
                        ((ISyndicationResource) op.Resource).Save(requestStream);
                    }
                    else if (op.Resource is IXmlSerializable)
                    {
                        mediaType = MediaType.Xml;

                        using (var xmlWriter = XmlWriter.Create(requestStream))
                        {
                            ((IXmlSerializable) op.Resource).WriteXml(xmlWriter);
                        }
                    }
                    else if (op.Resource is string)
                    {
                        mediaType = MediaType.Text;

                        using (var writer = new StreamWriter(requestStream))
                        {
                            writer.Write((string) op.Resource);
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }

                    if (op.ContentType != null)
                    {
                        mediaType = op.ContentType.Value;
                    }

                    var contentType = MediaTypeNames.GetMediaType(mediaType);

                    if (op.Files.Count > 0)
                    {
                        requestStream.Seek(0, SeekOrigin.Begin);
                        var part = new MimePart(requestStream) {ContentType = contentType};

                        using (var multipart = new MimeMessage(part))
                        {
                            contentType = new ContentType("multipart/related") {Boundary = multipart.Boundary}.ToString();

                            foreach (var file in op.Files)
                            {
                                var type = !string.IsNullOrEmpty(file.ContentType) ? file.ContentType : "application/octet-stream";
                                var disposition = new ContentDisposition(DispositionTypeNames.Attachment) {FileName = file.FileName};
                                part = new MimePart(file.Stream)
                                       {
                                           ContentType = type,
                                           ContentTransferEncoding = "binary",
                                           ContentDisposition = disposition
                                       };
                                multipart.Add(part);
                            }

                            multipart.WriteTo(stream);
                        }
                    }

                    request.ContentType = contentType;
                }
            }

            return request;
        }
コード例 #60
0
 /// <summary>
 /// Asynchronously send the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Asynchronously sends the specified message using the supplied sender and recipients.
 /// </remarks>
 /// <returns>An asynchronous task context.</returns>
 /// <param name="message">The message.</param>
 /// <param name="sender">The mailbox address to use for sending the message.</param>
 /// <param name="recipients">The mailbox addresses that should receive the message.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <para><paramref name="message"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="sender"/> is <c>null</c>.</para>
 /// <para>-or-</para>
 /// <para><paramref name="recipients"/> is <c>null</c>.</para>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> is not connected.
 /// </exception>
 /// <exception cref="ServiceNotAuthenticatedException">
 /// Authentication is required before sending a message.
 /// </exception>
 /// <exception cref="System.InvalidOperationException">
 /// <para>A sender has not been specified.</para>
 /// <para>-or-</para>
 /// <para>No recipients have been specified.</para>
 /// </exception>
 /// <exception cref="System.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public virtual Task SendAsync(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
 {
     return(SendAsync(DefaultOptions, message, sender, recipients, cancellationToken, progress));
 }