Example #1
0
 /// <summary>Initializes a new instance of <see cref="T:System.Net.Mail.AlternateView" /> with the specified file name and content type.</summary>
 /// <param name="fileName">The name of the file that contains the content for this alternate view.</param>
 /// <param name="contentType">The type of the content.</param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="fileName" /> is null.</exception>
 /// <exception cref="T:System.FormatException">
 ///   <paramref name="contentType" /> is not a valid value.</exception>
 /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
 /// <exception cref="T:System.IO.IOException">An I/O error occurred, such as a disk error.</exception>
 /// <exception cref="T:System.UnauthorizedAccessException">The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.</exception>
 public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base(fileName, contentType)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException();
     }
 }
 public static Attachment CreateAttachmentFromString(string content, ContentType contentType)
 {
     Attachment attachment = new Attachment();
     attachment.SetContentFromString(content, contentType);
     attachment.Name = contentType.Name;
     return attachment;
 }
Example #3
0
        public ActionResult Index()
        {
            var outParam = new SqlParameter
            {
                ParameterName = "@result",
                Direction = ParameterDirection.Output,
                SqlDbType = SqlDbType.Int
            };

            List<Boolean> _BUEvent = db.Database.SqlQuery<Boolean>("sp_InsertIntoBuEventLog @result OUT", outParam).ToList();

            using (TransactionScope transaction = new TransactionScope())
            {

                bool result = _BUEvent.FirstOrDefault();
                if (result)
                {
                    var _vwSendEmail = (db.vwSendEmails.Where(a => a.CREATEDDATE == CurrentDate).Select(a => new { a.KDKC, a.email, a.NMKC,a.TAHUN,a.BULAN,a.MINGGU })).Distinct();
                    int count = 0;
                    foreach(var sending in _vwSendEmail)
                    {
                        MemoryStream memory = new MemoryStream();
                        PdfDocument document = new PdfDocument() { Url = string.Format("http://*****:*****@gmail.com", "Legal-InHealth Reminder ");
                        message.Subject = SubjectName;
                        message.Attachments.Add(data);
                        message.Body = sending.NMKC;
                        SmtpClient client = new SmtpClient();

                        try
                        {
                            client.Send(message);
                        }
                        catch (Exception ex)
                        {

                            ViewData["SendingException"] = string.Format("Exception caught in SendErrorLog: {0}",ex.ToString());
                            return View("ErrorSending", ViewData["SendingException"]);
                        }
                        data.Dispose();
                        // Close the log file.
                        memory.Close();
                        count += 1;
                    }
                }
                transaction.Complete();
            }
            return View();
        }
        public XmlSerializationResult(object model,
                                      string contentType)
        {
            if (null == model)
            {
                throw new ArgumentNullException("model");
            }

            if (null == contentType)
            {
                throw new ArgumentNullException("contentType");
            }

            if (0 == contentType.Length)
            {
                throw new ArgumentOutOfRangeException("contentType");
            }

            ContentEncoding = Encoding.UTF8;
            ContentType = new ContentType(contentType).MediaType;

            var xml = model.XmlSerialize() as XmlDocument;
            if (null == xml)
            {
                return;
            }

            xml.CreateXmlDeclaration("1.0", "utf-8", null);
            xml.PreserveWhitespace = false;

            Content = xml.OuterXml;
        }
        private void ButtonSendClick(object sender, RoutedEventArgs e)
        {
            var teacherChoice = new TeacherChoice
                                    {
                                        Alternatives = GridDays.Children
                                            .OfType<RadioButton>()
                                            .Where(l => l.IsChecked.HasValue)
                                            .Select(l => l.DataContext)
                                            .Cast<Alternative>().ToList(),

                                        Email = Email,
                                        Name = FullName,
                                    };

            Options.IsEnabled = false;
            busyIndicator.IsBusy = true;

            var client = new SmtpClient("smtp.gmail.com", 587)
                             {
                                 Credentials = new NetworkCredential("*****@*****.**", "admin123."),
                                 EnableSsl = true,
                             };

            var contentType = new ContentType("text/xml") { Name = "teacherChoice.xml" };
            var xmlAttachment = Attachment.CreateAttachmentFromString(teacherChoice.Serialize(), contentType);
            var mail = new MailMessage("*****@*****.**", "*****@*****.**")
                           {
                               Subject = "Teste",
                           };
            mail.Attachments.Add(xmlAttachment);

            client.SendCompleted += ClientSendCompleted;
            client.SendAsync(mail, Token);
        }
		protected AttachmentBase (Stream contentStream, ContentType contentType)
		{
			if (contentStream == null || contentType == null)
				throw new ArgumentNullException ();
			this.contentStream = contentStream;
			this.contentType = contentType;
		}
        public void op_ToContentType_Encoding_string()
        {
            var expected = new ContentType("text/example; charset=utf-8");
            var actual = Encoding.UTF8.ToContentType("text/example");

            Assert.Equal(expected, actual);
        }
        public ActionResult NewApplication(TestInfo testInfo)
        {
            string response = "";
            if (ModelState.IsValid)
            {
                response = new RegisterRepository().RegisterTest(testInfo);

                MailMessage message = new MailMessage();
                string username = "******";
                string password = "******";
                string receiverEmail = testInfo.StudentInfo.AddressInfo.Email;
                ContentType mimeType = new ContentType("text/html");
                AlternateView alternate = AlternateView.CreateAlternateViewFromString("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"> <html><head><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\"></head><body><b>Dear " + testInfo.StudentInfo.FirstName + testInfo.StudentInfo.LastName + "</b>, <br /><br /><br />Greetings from IELTS !!! <br/><br/><br/> Your registration was successful. Thank You for registering IELTS Examination. <br/> <br/> <br/> Please see below the registration details <br/> <b>&nbsp;&nbsp;&nbsp;&nbsp;Your Receipt Number  :</b> " + testInfo.ReceiptNumber + ".<br /><b>&nbsp;&nbsp;&nbsp;&nbsp;Registered Date Time  :</b> " + testInfo.CreatedDate.ToString() + "<br /><br /> <b>Note: </b> Receipt Number and Passport or National Identity Card is mandatory to check your test results. <br /><br /><br /> Thank You,<br/><br/><br/> IELTS Admin</body></html>.", mimeType);
                message.From = new MailAddress(username);
                message.To.Add(receiverEmail);
                message.Subject = "IELTS Registration - Congrats, " + testInfo.StudentInfo.FirstName + " " + testInfo.StudentInfo.LastName + "!";
                //message.Body = "<html><head></head><body><b>Dear " + testInfo.StudentInfo.FirstName + testInfo.StudentInfo.LastName + "</b>, <br /><br /><br />Greetings from IELTS !!! <br/> Your registration was successful. Thank You for registering IELTS Examination. <br/> Please see below the registration details <br/> <dd /><b>Your Receipt Number  :</b> " + testInfo.ReceiptNumber + ".<br /><dd /><b>Registered Date Time  :</b> "+testInfo.CreatedDate.ToString()+"<br /><br /> <b>Note: </b> Receipt Number is mandatory to check your test results. <br /><br /><br /> Thank You, IELTS Admin</body></html>.";
                message.AlternateViews.Add(alternate);
                message.IsBodyHtml = true;
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(username, password);
                smtpClient.Send(message);
                RedirectToAction("SubmitApplicationForm");
            }
            return View(testInfo);
        }
Example #9
0
        public static MailMessage CreateMailMessage(DataTable t, string mailType, string subject, string mailto)
        {
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress(ConfigurationManager.AppSettings["MailUserName"]);
            mail.To.Add(mailto);
            mail.Subject = subject;

            EmailTemplateModel model = new EmailTemplateModel(mailType);

            model.Content = TemplateCreator.ConvertDatatableToHtml(t);

            string html = TemplateCreator.CreateEmailTemplate <EmailTemplateModel>(model);

            ContentType   mimeType = new System.Net.Mime.ContentType("text/html");
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(html, mimeType);

            Images[mailType + "Banner"].ContentId        = "banner";
            Images[mailType + "Banner"].TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlView.LinkedResources.Add(Images[mailType + "Banner"]);

            Images["MicrosoftLogoFooter"].ContentId        = "footer";
            Images["MicrosoftLogoFooter"].TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlView.LinkedResources.Add(Images["MicrosoftLogoFooter"]);;

            mail.AlternateViews.Add(htmlView);
            return(mail);
        }
 /// <summary>
 /// 发送邮件并可发送附件
 /// </summary>
 /// <param name="isBodyHtml">发送的内容是否为html格式</param>
 /// <returns>是否发送成功</returns>
 public bool SendEmailWithAttachment(bool isBodyHtml = false)
 {
     try
     {
         // SmtpClient要发送的邮件实例
         MailMessage message = new MailMessage();
         message.From            = new MailAddress(FromAddress);
         message.Subject         = Subject;
         message.SubjectEncoding = Encoding.UTF8; //标题编码
         message.Body            = Body;
         message.BodyEncoding    = Encoding.UTF8; //邮件内容编码
         message.IsBodyHtml      = isBodyHtml;
         foreach (var to in ToAddressList)
         {
             //添加接收人地址
             message.To.Add(new MailAddress(to));
         }
         //添加邮件附件
         foreach (var file in FileList)
         {
             //添加附件
             // 为邮件创建文件附件对象
             Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
             // Add time stamp information for the file.
             //为文件添加时间戳信息。
             ContentDisposition disposition = data.ContentDisposition;
             disposition.CreationDate     = System.IO.File.GetCreationTime(file);
             disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
             disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);
             // Add the file attachment to this e-mail message.
             //将文件附件添加到该电子邮件。
             message.Attachments.Add(data);
             //data.Dispose();
         }
         //添加纯文本格式的替代邮件内容
         foreach (var body in AlternateViews)
         {
             ContentType mimeType = new System.Net.Mime.ContentType("text/html");
             // Add the alternate body to the message.
             AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
             message.AlternateViews.Add(alternate);
         }
         //创建基于密码的身份验证方案
         NetworkCredential nc     = new NetworkCredential(FromAddress, Password);
         SmtpClient        client = new SmtpClient(Server);
         //表示以当前登录用户的默认凭据进行身份验证
         client.UseDefaultCredentials = true;
         client.Credentials           = nc;                                         //设置验证发件人的身份凭证
         client.DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network; //待发的电子邮件通过网络发送到smtp服务器
         //Send the message.
         //正式发送信息
         client.Send(message);
         return(true);
     }
     catch (Exception ex)
     {
         SystemLogHelper.Error(MethodBase.GetCurrentMethod(), "发送邮件失败_SendEmailWithAttachment", ex);
         return(false);
     }
 }
        public void op_ToContentType_EncodingDefault_string()
        {
            var expected = new ContentType("text/example; charset=Windows-1252");
            var actual = Encoding.Default.ToContentType("text/example");

            Assert.Equal(expected, actual);
        }
Example #12
0
        private void SendNotification(string to, string subject, string body)
        {
            try
            {
                SmtpClient  sclient = new SmtpClient(ReportFormatter._smtpserver);
                MailAddress Bcc     = new MailAddress(ReportFormatter._bccEmailList);

                // create and send the SMTP message
                System.Net.Mail.MailMessage emsg = new MailMessage(_from, to, subject, body); //sb.ToString());

                ContentType mimeType = new System.Net.Mime.ContentType("text/html");
                // Add the alternate body to the message.

                AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
                emsg.AlternateViews.Add(alternate);
                emsg.Bcc.Add(Bcc);
                sclient.Send(emsg);
            }
            catch (System.Net.Mail.SmtpException sme)
            {// exception handling
                LogFileMgr.Instance.WriteToLogFile("ReportFormatter::SendNotification():ECaught:" + sme.Message);
            }
            catch (SystemException se)
            {// exception handling
                LogFileMgr.Instance.WriteToLogFile("ReportFormatter::SendNotification():ECaught:" + se.Message);
            }
        }
Example #13
0
 public MailAttachment(ContentType contentType, string fileName, MemoryStream fileStream)
 {
     this._ContentType = contentType;
     this._FileStream = fileStream;
     this._Name = fileName;
     this._ByteArray = CommonHelper.StreamToByteArray(fileStream);
 }
Example #14
0
 public Content(int id, string source, string description, ContentType contentType)
     : base(id)
 {
     Source = source;
     Description = description;
     ContentType = contentType;
 }
Example #15
0
        public void RestorePassword(string mail)
        {
            var user = provider.GetByMail(mail);

            if (user == null)
            {
                return;
            }

            using (var client = new SmtpClient())
            {
                var token   = Resolver.GetSingleton <Encryptor>().GenerateToken(user);
                var host    = System.Web.HttpContext.Current.Request.Url.Authority;
                var subject = Resources.ResourceAccessor
                              .Instance.Get("ForgotPasswordPage");
                var style = Resources.ResourceAccessor
                            .Instance.Get("ForgotMailTemplateStyle");
                var body = Resources.ResourceAccessor
                           .Instance.Get("ForgotMailTemplate")
                           .FormatWith(user.Name, host, user.Id, token);

                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("*****@*****.**");
                msg.To.Add(mail);
                msg.Subject    = subject;
                msg.IsBodyHtml = true;
                msg.Body       = style + body;
                ContentType   mimeType  = new System.Net.Mime.ContentType("text/html");
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
                msg.AlternateViews.Add(alternate);
                msg.Priority = MailPriority.High;

                client.Send(msg);
            }
        }
Example #16
0
 public MailAttachment(ContentType contentType, string fileName, byte[] byteArray)
 {
     this._ContentType = contentType;
     this._ByteArray = byteArray;
     this._Name = fileName;
     this._FileStream = CommonHelper.ByteArrayToStream(byteArray);
 }
Example #17
0
 internal void SetContentType(System.Net.Mime.ContentType contentType)
 {
     this._contentType           = contentType;
     this._contentType.MediaType = MimeReader.GetMediaType(contentType.MediaType);
     this._mediaMainType         = MimeReader.GetMediaMainType(contentType.MediaType);
     this._mediaSubType          = MimeReader.GetMediaSubType(contentType.MediaType);
 }
 public static Task<SendInstantMessageResult> SendInstantMessageAsync(this 
     InstantMessagingFlow flow, ContentType contentType, 
     byte[] body)
 {
     return Task<SendInstantMessageResult>.Factory.FromAsync(flow.BeginSendInstantMessage,
         flow.EndSendInstantMessage, contentType, body, null);
 }
 internal DataWebRequest(Uri uri, Byte[] data, ContentType contentType)
 {
     //only called internally (from factory) so we trust the params to be valid
     this.uri = uri;
     this.data = data;
     this.contentType = contentType;
 }
        public static async Task HandleGetFileRequestAsync(HttpRequest request, HttpResponse response, IHostingEnvironment env)
        {
            IFileInfo fileInfo = request.Path.GetContentFileInfo(env.WebRootFileProvider);

            if (fileInfo.Exists)
            {
                System.Net.Mime.ContentType contentType = ResponseHelper.ContentTypeFromName(fileInfo.Name);
                contentType.Name     = fileInfo.Name;
                response.ContentType = contentType.ToString();
                response.StatusCode  = StatusCodes.Status200OK;
                await response.SendFileAsync(fileInfo);
            }
            else if (fileInfo is GetFileError)
            {
                await SendErrorResponseAsync(response, "Error locating resource", env, tw =>
                {
                    tw.WriteString("Unexpected error locating file at ");
                    tw.WriteElementString("code", fileInfo.Name);
                    tw.WriteString(".");
                }, ((GetFileError)fileInfo).Error);
            }
            else
            {
                await SendErrorResponseAsync(response, "Error locating resource", env, tw =>
                {
                    tw.WriteString("Unable to locate file at ");
                    tw.WriteElementString("code", fileInfo.Name);
                    tw.WriteString(".");
                }, ((GetFileError)fileInfo).Error);
            }
        }
		protected AttachmentBase (string fileName)
		{
			if (fileName == null)
				throw new ArgumentNullException ();
			contentStream = File.OpenRead (fileName);
			contentType = new ContentType (MimeTypes.GetMimeType (fileName));
		}
Example #22
0
 /// <summary>Initializes a new instance of <see cref="T:System.Net.Mail.LinkedResource" /> with the specified file name and content type.</summary>
 /// <param name="fileName">The file name that holds the content for this embedded resource.</param>
 /// <param name="contentType">The type of the content.</param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="fileName" /> is null.</exception>
 /// <exception cref="T:System.FormatException">
 ///   <paramref name="contentType" /> is not a valid value.</exception>
 public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base(fileName, contentType)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException();
     }
 }
		public async Task<ValidateResult> Validate(HttpRequestBase request, HttpResponseBase response)
		{
			request.ThrowIfNull("request");
			response.ThrowIfNull("response");

			if (!String.IsNullOrEmpty(request.ContentType))
			{
				try
				{
					var contentType = new ContentType(request.ContentType);

					if (String.Equals(contentType.MediaType, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) || String.Equals(contentType.MediaType, "multipart/form-data", StringComparison.OrdinalIgnoreCase))
					{
						ValidationResult validationResult = await _antiCsrfNonceValidator.ValidateAsync(request);
						ResponseResult responseResult = await _antiCsrfResponseGenerator.GetResponseAsync(validationResult);

						if (responseResult.ResultType == ResponseResultType.ResponseGenerated)
						{
							return ValidateResult.ResponseGenerated(responseResult.Response);
						}
					}
				}
				catch (FormatException)
				{
				}
			}

			await _antiCsrfCookieManager.ConfigureCookieAsync(request, response);

			return ValidateResult.RequestValidated();
		}
Example #24
0
 public HTTPHeader()
 {
     Headers        = new NameValueCollection();
     ContentType    = new System.Net.Mime.ContentType(MediaTypeNames.Text.Html);
     CacheControl   = "no-cache";
     _ContentLength = 0;
 }
Example #25
0
        static void Main(string[] args)
        {
            HttpWebRequest request = WebRequest.Create("https://www.baidu.com/") as HttpWebRequest;
            request.Method = "GET";
            request.AddRange("bytes", 0, 1000);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            ContentType content = new ContentType();
            foreach (string header in response.Headers)
            {
                Console.WriteLine("{0}:{1}", header, response.Headers[header]);
            }
            var stream = response.GetResponseStream();
            //int count = (int)response.ContentLength;
            //byte[] bytes = new byte[count];
            //stream.Read(bytes, 0, count);
            //var str = Encoding.UTF8.GetString(bytes);

            using (StreamReader reader = new StreamReader(stream))
            {
                StreamWriter writer = new StreamWriter("index.html");
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    writer.WriteLine(line);
                }
            }

            Console.WriteLine("ok");
            Console.ReadKey();
        }
Example #26
0
        /// <summary>
        /// Parses a <see cref="NameValueCollection"/> to a MessageHeader
        /// </summary>
        /// <param name="headers">The collection that should be traversed and parsed</param>
        /// <returns>A valid MessageHeader object</returns>
        /// <exception cref="ArgumentNullException">If <paramref name="headers"/> is <see langword="null"/></exception>
        internal MessageHeader(NameValueCollection headers)
        {
            if (headers == null)
                throw new ArgumentNullException("headers");

            // Create empty lists as defaults. We do not like null values
            // List with an initial capacity set to zero will be replaced
            // when a corrosponding header is found
            To = new List<RfcMailAddress>(0);
            Cc = new List<RfcMailAddress>(0);
            Bcc = new List<RfcMailAddress>(0);
            Received = new List<Received>();
            Keywords = new List<string>();
            InReplyTo = new List<string>(0);
            References = new List<string>(0);
            DispositionNotificationTo = new List<RfcMailAddress>();
            UnknownHeaders = new NameValueCollection();

            // Default importancetype is Normal (assumed if not set)
            Importance = MailPriority.Normal;

            // 7BIT is the default ContentTransferEncoding (assumed if not set)
            ContentTransferEncoding = ContentTransferEncoding.SevenBit;

            // text/plain; charset=us-ascii is the default ContentType
            ContentType = new ContentType("text/plain; charset=us-ascii");

            // Now parse the actual headers
            ParseHeaders(headers);
        }
Example #27
0
        private static AlternateView ImportText(StringReader r, string encoding, System.Net.Mime.ContentType contentType)
        {
            string        line = string.Empty;
            StringBuilder b    = new StringBuilder();

            while ((line = r.ReadLine()) != null && line != ".")
            {
                switch (encoding)
                {
                case "quoted-printable":
                    if (line.EndsWith("="))
                    {
                        b.Append(DecodeQP(line.TrimEnd('=')));
                    }
                    else
                    {
                        b.Append(DecodeQP(line) + "\n");
                    }
                    break;

                case "base64":
                    b.Append(DecodeBase64(line, contentType.CharSet));
                    break;

                default:
                    b.Append(line);
                    break;
                }
            }

            AlternateView returnValue = AlternateView.CreateAlternateViewFromString(b.ToString(), null, contentType.MediaType);

            returnValue.TransferEncoding = TransferEncoding.QuotedPrintable;
            return(returnValue);
        }
Example #28
0
        /// <summary>
        /// Creates an entity from the <paramref name="parts"/> of which the first part must be the content and the second
        /// part the signature..
        /// </summary>
        /// <param name="contentType">The content type header for the new entity.</param>
        /// <param name="parts">The body parts, which must consist of two parts, of which the first must be the content and the second part the signature</param>
        public SignedEntity(ContentType contentType, IEnumerable<MimeEntity> parts)
            : base(contentType)
        {
            if (parts == null)
            {
                throw new ArgumentNullException("parts");
            }
            
            int count = 0;

            foreach(MimeEntity part in parts)
            {
                switch(count)
                {
                    default:
                        throw new SignatureException(SignatureError.InvalidSignedEntity);
                    
                    case 0:
                        Content = part;
                        break;
                    
                    case 1:
                        Signature = part;
                        break;
                }                
                ++count;
            }
        }
Example #29
0
        private static System.Net.Mime.ContentType FindContentType(NameValueCollection headers)
        {
            System.Net.Mime.ContentType returnValue = new ContentType();
            if (headers["content-type"] == null)
            {
                return(returnValue);
            }
            returnValue = new System.Net.Mime.ContentType(Regex.Match(headers["content-type"], @"^([^;]*)", RegexOptions.IgnoreCase).Groups[1].Value);
            if (Regex.IsMatch(headers["content-type"], @"name=""?(.*?)""?($|;)", RegexOptions.IgnoreCase))
            {
                returnValue.Name = Regex.Match(headers["content-type"], @"name=""?(.*?)""?($|;)", RegexOptions.IgnoreCase).Groups[1].Value;
            }
            if (Regex.IsMatch(headers["content-type"], @"boundary=""(.*?)""", RegexOptions.IgnoreCase))
            {
                returnValue.Boundary = Regex.Match(headers["content-type"], @"boundary=""(.*?)""", RegexOptions.IgnoreCase).Groups[1].Value;
            }
            else if (Regex.IsMatch(headers["content-type"], @"boundary=(.*?)(;|$)", RegexOptions.IgnoreCase))
            {
                returnValue.Boundary = Regex.Match(headers["content-type"], @"boundary=(.*?)(;|$)", RegexOptions.IgnoreCase).Groups[1].Value;
            }
            if (Regex.IsMatch(headers["content-type"], @"charset=""(.*?)""", RegexOptions.IgnoreCase))
            {
                returnValue.CharSet = Regex.Match(headers["content-type"], @"charset=""(.*?)""", RegexOptions.IgnoreCase).Groups[1].Value;
            }

            return(returnValue);
        }
Example #30
0
        public void Build(OutlookEventEntity outlookEvent, MailMessage message, String emailBody, int releaseDuration, string organizer)
        {
            var builder = new StringBuilder();
            builder.AppendLine("BEGIN:VCALENDAR");
            builder.AppendLine("PRODID:~//Schedule a meeting");
            builder.AppendLine("VERSION:2.O");
            builder.AppendLine(String.Format("METHOD:{0}", outlookEvent.OutlookEmailMethod));
            builder.AppendLine("BEGIN:VEVENT");
            builder.AppendLine(String.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", outlookEvent.StartTime.ToUniversalTime()));
            builder.AppendLine(String.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", SystemTime.Now));
            builder.AppendLine(String.Format("DTEND:{0:yyyyMMddTHHmmssZ}", outlookEvent.StartTime.AddMinutes(releaseDuration).ToUniversalTime()));
            builder.AppendLine(String.Format("LOCATION:{0}", outlookEvent.Location));
            builder.AppendLine(String.Format("UID:{0}", outlookEvent.AppointmentId));
            builder.AppendLine(String.Format("DESCRIPTION:{0}", emailBody));
            builder.AppendLine(String.Format(
                "X-ALT-DESC;FMTTYPE=text/html:{0}", emailBody));
            builder.AppendLine(String.Format("SUMMARY:{0}", message.Subject));
            builder.AppendLine(String.Format("ORGANIZER:MAILTO:{0}", organizer));
            builder.AppendLine(String.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", message.To[0].DisplayName,
                message.To[0].Address));
            builder.AppendLine("BEGIN:VALARM");
            builder.AppendLine("TRIGGER:-PT15M");
            builder.AppendLine("ACTION:DISPLAY");
            builder.AppendLine("DESCRIPTION:Reminder");
            builder.AppendLine("END:VALARM");
            builder.AppendLine("END:VEVENT");
            builder.AppendLine("END:VCALENDAR");

            var contentType = new ContentType("text/calendar");
            contentType.Parameters.Add("method", "REQUEST");
            contentType.Parameters.Add("name", "Meeting.ics");
            var alternateView = AlternateView.CreateAlternateViewFromString(builder.ToString(), contentType);

            message.AlternateViews.Add(alternateView);
        }
        public static bool Send(string email, MemoryStream stream, string fileName)
        {
            try
            {
                stream.Position = 0;
                System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(MediaTypeNames.Application.Pdf);
                Attachment attachment = new Attachment(stream, contentType);
                attachment.ContentDisposition.FileName = $"{fileName}.pdf";
                MailMessage message = new MailMessage();
                SmtpClient  client  = new SmtpClient("smtp.gmail.com");
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(email);
                message.Subject    = "Pdf Dosyası";
                message.Body       = "Yüklenmiş olduğunuz dosyanız word formatından pdf formatına dönüştürülmüştür";
                message.IsBodyHtml = true;
                message.Attachments.Add(attachment);

                client.Host                  = "smtp.gmail.com";
                client.Port                  = 587;
                client.EnableSsl             = true;
                client.DeliveryMethod        = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential("*****@*****.**", "**");
                client.Send(message);
                stream.Close();
                stream.Dispose();
                return(true);
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
        }
        private bool SendSTMPT(byte[] bytes, string correo)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(correo);
                mail.Subject = "Orden de salida";
                mail.Body    = "AVS Orden de salida, no responder";
                System.Net.Mail.Attachment attachment;

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType();
                ct.MediaType = MediaTypeNames.Application.Pdf;
                ct.Name      = "output " + DateTime.Now.ToString() + ".pdf";

                attachment = new System.Net.Mail.Attachment(new MemoryStream(bytes), ct);
                mail.Attachments.Add(attachment);
                SmtpServer.Port                  = 587;
                SmtpServer.Host                  = "smtp.gmail.com";
                SmtpServer.EnableSsl             = true;
                SmtpServer.UseDefaultCredentials = false;
                SmtpServer.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "avs123456");
                SmtpServer.Send(mail);


                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #33
0
 /// <summary>Initializes a new instance of <see cref="T:System.Net.Mail.LinkedResource" /> with the values supplied by <see cref="T:System.IO.Stream" /> and <see cref="T:System.Net.Mime.ContentType" />.</summary>
 /// <param name="contentStream">A stream that contains the content for this embedded resource.</param>
 /// <param name="contentType">The type of the content.</param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="contentStream" /> is null.</exception>
 /// <exception cref="T:System.FormatException">
 ///   <paramref name="contentType" /> is not a valid value.</exception>
 public LinkedResource(Stream contentStream, System.Net.Mime.ContentType contentType) : base(contentStream, contentType)
 {
     if (contentStream == null)
     {
         throw new ArgumentNullException();
     }
 }
Example #34
0
        internal void SetContentFromString(string contentString, System.Net.Mime.ContentType contentType)
        {
            Encoding aSCII;

            if (contentString == null)
            {
                throw new ArgumentNullException("content");
            }
            if (this.part.Stream != null)
            {
                this.part.Stream.Close();
            }
            if ((contentType != null) && (contentType.CharSet != null))
            {
                aSCII = Encoding.GetEncoding(contentType.CharSet);
            }
            else if (MimeBasePart.IsAscii(contentString, false))
            {
                aSCII = Encoding.ASCII;
            }
            else
            {
                aSCII = Encoding.GetEncoding("utf-8");
            }
            byte[] bytes = aSCII.GetBytes(contentString);
            this.part.SetContent(new MemoryStream(bytes), contentType);
            if (MimeBasePart.ShouldUseBase64Encoding(aSCII))
            {
                this.part.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            }
            else
            {
                this.part.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            }
        }
Example #35
0
        public Task SendAsync(IdentityMessage message, Stream attachment, string CC = null)
        {
            SmtpClient  smtp = new SmtpClient();
            MailMessage mail = new MailMessage();

            mail.From = new MailAddress(ConfigurationManager.AppSettings["systemEmail"]);
            mail.To.Add(message.Destination);
            mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["ordersEmail"]));
            mail.Bcc.Add(new MailAddress(ConfigurationManager.AppSettings["developerIdentity"]));
            mail.Subject = message.Subject;

            if (attachment != null)
            {
                System.Net.Mime.ContentType ct     = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                System.Net.Mail.Attachment  attach = new System.Net.Mail.Attachment(attachment, ct);
                attach.ContentDisposition.FileName = "Locarno Sun Dried Fruit Order";

                mail.Attachments.Add(attach);
            }

            string        body     = string.Format("<html><body><table>{0}<tr><td><br />Thank you for using the &copy; Locarno Sun Dried Fruit platform</td></tr><tr><td><br /><img src=cid:LogoImage></td></tr></table></body></html>", message.Body);
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body.Trim(), null, "text/html");

            string fileNameLogo = HttpContext.Current.Server.MapPath("~/Content/Images/Logopng.png");

            System.Net.Mail.LinkedResource imageResource = new System.Net.Mail.LinkedResource(fileNameLogo, "image/png");
            imageResource.ContentId = "LogoImage";
            htmlView.LinkedResources.Add(imageResource);

            mail.AlternateViews.Add(htmlView);

            smtp.Send(mail);

            return(Task.FromResult(0));
        }
 public object Deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat)
 {
     string input = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
     MethodInfo deserialize = typeof(JavaScriptSerializer).GetMethod("Deserialize", new Type[] { typeof(string) });
     MethodInfo deserializeForType = deserialize.MakeGenericMethod(bindingContext.ModelType);
     return deserializeForType.Invoke(new JavaScriptSerializer(), new object[] { input });
 }
        private void _sendMail(byte[] receipt, string mail_id, string receipt_no, string receipt_date, string body)
        {
            string FromMail = donotreplyMail;
            string ToMail   = mail_id;
            string Subject  = "Thanks For The Payment. Your Receipt No: " + receipt_no; //"Attendance Sheet of class " + class_name + " date " + DateTime.Now.Date.ToString("dd/MM/yyyy");
            string Body     = body;

            var memStream = new MemoryStream(receipt);

            memStream.Position = 0;
            var contentType      = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
            var reportAttachment = new Attachment(memStream, contentType);

            reportAttachment.ContentDisposition.FileName = "Fees_receipt.pdf";


            if (ToMail != null)
            {
                using (MailMessage mm = new MailMessage(
                           FromMail, ToMail, Subject, Body))
                {
                    mm.Attachments.Add(reportAttachment);
                    //mm.Attachments.Add(new Attachment(new MemoryStream(receipt), "Fees_Receipt.pdf", MediaTypeNames.Application.Pdf));
                    mm.IsBodyHtml = true;
                    SmtpClient        smtp = new SmtpClient();
                    NetworkCredential networkCredential = new NetworkCredential(FromMail, donotreplyMailPassword);
                    smtp.Credentials = networkCredential;
                    smtp.EnableSsl   = true;
                    smtp.Host        = "smtp.gmail.com";
                    smtp.Port        = 587;
                    smtp.Send(mm);
                }
            }
        }
        public void op_ToContentType_EncodingNull_string()
        {
            var expected = new ContentType("text/example");
            var actual = (null as Encoding).ToContentType("text/example");

            Assert.Equal(expected, actual);
        }
Example #39
0
 public HTTPHeader()
 {
     Headers = new NameValueCollection();
     ContentType = new System.Net.Mime.ContentType(MediaTypeNames.Text.Html);
     CacheControl = "no-cache";
     _ContentLength = 0;
 }
Example #40
0
 public static bool SupportsContentType(ContentType contentType)
 {
     for(int i = 0; i != SupportedContentTypes.Length; ++i)
         if(SupportedContentTypes[i].Equals(contentType.MediaType))
             return true;
     return false;
 }
Example #41
0
        public virtual void Write(JsonWriter writer, HttpContent content)
        {
            if (content == null)
                return;

            var bytes = content.ReadAsByteArrayAsync().ConfigureAwait(false).GetAwaiter().GetResult();

            IEnumerable<string> contentTypeValues;
            string contentTypeHeaderValue;
            if (content.Headers.TryGetValues("Content-Type", out contentTypeValues))
                contentTypeHeaderValue = contentTypeValues.Last();
            else
                contentTypeHeaderValue = "text/html; charset=utf-8";

            writer.WritePropertyName("format");

            var contentType = new ContentType(contentTypeHeaderValue);
            bool formatAsBinary = false;
            var encoding = Encoding.ASCII;
            if (contentType.CharSet != null)
                encoding = Encoding.GetEncoding(contentType.CharSet);
            else
                formatAsBinary = bytes.Any(c => c == 0 || c > 127);
            if (formatAsBinary)
            {
                writer.WriteValue("binary");
                writer.WritePropertyName("body");
                writer.WriteValue(Convert.ToBase64String(bytes));
            }
            else
            {
                // Need to use memory stream to avoid UTF-8 BOM weirdness
                string str;
                using (var ms = new MemoryStream(bytes))
                {
                    using (var sr = new StreamReader(ms, encoding))
                    {
                        str = sr.ReadToEnd();
                    }
                }

                if (contentType.MediaType == "application/json" || contentType.MediaType.EndsWith("+json"))
                {
                    var jtoken = JToken.Parse(str);
                    writer.WriteValue("json");
                    writer.WritePropertyName("body");
                    jtoken.WriteTo(writer);
                }
                else
                {
                    writer.WriteValue("text");
                    writer.WritePropertyName("body");
                    //writer.WriteValue(str);

                    // Represent the text as an array of strings split at \r\n to make long text content easier to read.
                    WriteStringFomat(writer, contentType, str);
                }
            }
        }
        public Task<bool> SendMail(string sendToEmail, BitmapEncoder bitmap)
        {

            bool returnValue = true;

            MailMessage msg = new MailMessage("*****@*****.**", sendToEmail, "Your Microsoft Kinect Photo Booth Picture", body);
            
                msg.BodyEncoding = System.Text.Encoding.Unicode;
                msg.IsBodyHtml = true;    
            ContentType ct = new ContentType();
            ct.MediaType = MediaTypeNames.Image.Jpeg;
            ct.Name = "MSKinectPhotobooth.png";

            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream);
            stream.Position = 0;
            Attachment data = new Attachment(stream, "MSPhotobooth.png");
            msg.Attachments.Add(data);
            Task<bool> t = new Task<bool>(() =>
            {
                try
                {


                    //SmtpClient smtpClient = new SmtpClient("smtp.office365.com")
                    SmtpClient smtpClient = new SmtpClient(_SMTPEmailServer)
                    {
                        UseDefaultCredentials = false,
                        
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential(_SMTPEmailUserID, _SMTPEmailPassword),
                    };

                    smtpClient.Send(msg);
                    smtpClient.Dispose();
                }
                catch (Exception ex)
                {
                    
                     returnValue = false;
                }
                finally
                {
                    msg.Dispose();
                }

                return returnValue;
            });

            t.Start();




            return t;



        }
Example #43
0
 public MimeEntity()
 {
     this._children       = new List <MimeEntity>();
     this._headers        = new NameValueCollection();
     this._contentType    = MimeReader.GetContentType(string.Empty);
     this._parent         = null;
     this._encodedMessage = new StringBuilder();
 }
Example #44
0
 public bool CanDeserialize(ContentType contentType) {
     for (int i = 0; i < this.RequestFormatHandlers.Count; ++i) {
         if (this.RequestFormatHandlers[i].CanDeserialize(contentType)) {
             return true;
         }
     }
     return false;
 }
Example #45
0
 public bool CanSerialize(ContentType responseFormat) {
     for (int i = 0; i < this.ResponseFormatHandlers.Count; ++i) {
         if (this.ResponseFormatHandlers[i].CanSerialize(responseFormat)) {
             return true;
         }
     }
     return false;
 }
Example #46
0
 public ApiWorkerRequest(string page, string query, TextWriter output, HttpContextBase context, ContentType contentType):base(page,query,output)
 {
     if (context == null) throw new ArgumentNullException("context");
     _output = output;
     _context = context;
     _contentType = contentType;
     ResponseHeaders = new NameValueCollection();
 }
 public BundlerHttpHandler(IEnumerable<BundleResource> bundleResources, string token, string verison,
                           ContentType contentType)
 {
     _bundleResources = new Queue<BundleResource>(bundleResources);
     _token = token;
     _verison = verison;
     _contentType = contentType;
 }
Example #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeEntity"/> class.
 /// </summary>
 public MimeEntity()
 {
     _children = new List<MimeEntity>();
     _headers = new NameValueCollection();
     _contentType = MimeReader.GetContentType(string.Empty);
     _parent = null;
     _encodedMessage = new StringBuilder();
 }
Example #49
0
        public void Send_Email_2()
        {
            MailMessage message = new MailMessage(
                "*****@*****.**",
                "*****@*****.**");

            // Construct the alternate body as HTML.
            //string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
            //body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
            //body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
            //body += "</FONT></DIV></BODY></HTML>";

            message.Subject = "This is Testing Email";


            //message.IsBodyHtml = true;
            //string body = "<!DOCTYPE HTML>";
            //body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=UTF-8\">";
            //body += "</HEAD><BODY><DIV><p><font size=2.5 face='Century Gothic'>Hello</font>";
            //body += "</DIV></BODY></HTML>";
            string sHtml = "<HTML>\n" +
                           "<HEAD>\n" +
                           "<TITLE>Sample GIF</TITLE>\n" +
                           "</HEAD>\n" +
                           "<BODY><P>\n" +
                           "<h1><Font Color=Green>Inline graphics</Font></h1></P>\n" +
                           "</BODY>\n" +
                           "</HTML>";



            message.Body = sHtml;

            ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            // Add the alternate body to the message.

            AlternateView alternate = AlternateView.CreateAlternateViewFromString(sHtml, mimeType);

            message.AlternateViews.Add(alternate);

            // Send the message.
            //SmtpClient client = new SmtpClient(server);
            //client.Credentials = CredentialCache.DefaultNetworkCredentials;

            SmtpClient smtp = new SmtpClient();

            // smtp.Host = "smtp.gmail.com";
            smtp.Host = "smtpout.secureserver.net";
            // smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential("*****@*****.**", "123nir");

            smtp.UseDefaultCredentials = true;
            smtp.Credentials           = NetworkCred;
            //smtp.Port = 587;
            smtp.Port = 80;
            smtp.Send(message);
        }
 /// <summary>Instantiates an <see cref="T:System.Net.Mail.AttachmentBase" /> with the specified <see cref="T:System.IO.Stream" /> and <see cref="T:System.Net.Mime.ContentType" />.</summary>
 /// <param name="contentStream">A stream containing the content for this attachment.</param>
 /// <param name="contentType">The type of the content.</param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="contentStream" /> is null.</exception>
 /// <exception cref="T:System.FormatException">
 ///   <paramref name="contentType" /> is not a valid value.</exception>
 protected AttachmentBase(Stream contentStream, System.Net.Mime.ContentType contentType)
 {
     if (contentStream == null || contentType == null)
     {
         throw new ArgumentNullException();
     }
     this.contentStream = contentStream;
     this.contentType   = contentType;
 }
 /// <summary>Instantiates an <see cref="T:System.Net.Mail.AttachmentBase" /> with the specified file name and content type.</summary>
 /// <param name="fileName">The file name holding the content for this attachment.</param>
 /// <param name="contentType">The type of the content.</param>
 /// <exception cref="T:System.ArgumentNullException">
 ///   <paramref name="fileName" /> is null.</exception>
 /// <exception cref="T:System.FormatException">
 ///   <paramref name="contentType" /> is not a valid value.</exception>
 protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException();
     }
     this.contentStream = File.OpenRead(fileName);
     this.contentType   = contentType;
 }
Example #52
0
        /// <summary>
        /// Sends the given message
        /// </summary>
        public void SendEmail(EmailingMessage mail)
        {
            try
            {
                MailMessage objMessage = new MailMessage();

                SmtpClient smtp = new SmtpClient(EmailConfig.SmtpServer);

                // Check if server requires authentication
                if (EmailConfig.PALEmailSMTPServerAuthUserName != null)
                {
                    smtp.Credentials    = new NetworkCredential(EmailConfig.PALEmailSMTPServerAuthUserName, EmailConfig.PALEmailSMTPServerAuthPassword);
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                }

                objMessage.To.Add(mail.ToEmail);
                objMessage.From    = new MailAddress((mail.FromName == null) ? mail.FromEmail : "\"" + mail.FromName + "\" <" + mail.FromEmail + ">");
                objMessage.Subject = mail.Subject;

                ContentType htmlMimeType = new System.Net.Mime.ContentType("text/html");
                mail.Format = EmailFormat.Html;
                // Construct the body as HTML.
                string bodyHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
                bodyHtml += "<html><head><meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
                bodyHtml += "</head><body><div><font size=\"2\" face=\"arial\">" + mail.Body;
                bodyHtml += "</font></div></body></html>";

                //AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(bodyHtml, null, "text/html");
                //alternateHtml.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
                //objMessage.AlternateViews.Add(alternateHtml);

                objMessage.Body       = bodyHtml;          //.Replace("<br />", "");
                objMessage.IsBodyHtml = true;
                //ContentType mimeType = new System.Net.Mime.ContentType("text/plain");
                //// Construct the body as TEXT.
                //string bodyPlain="";
                //if(mail.Format!= EmailFormat.Html)
                //bodyPlain = StripHTML(mail.Body);
                //bodyPlain = mail.Body.Replace("<br />", "");
                //AlternateView alternatePlain = AlternateView.CreateAlternateViewFromString(bodyPlain, null, "text/plain");
                //alternatePlain.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
                //objMessage.AlternateViews.Add(alternatePlain);

                objMessage.BodyEncoding = System.Text.Encoding.UTF8;

                smtp.Port      = Int32.Parse(EmailConfig.SmtpServerPort);
                smtp.EnableSsl = Boolean.Parse(EmailConfig.SmtpServerEnableSSL);
                smtp.Send(objMessage);
                System.Threading.Thread.Sleep(500);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #53
0
        private bool SendEmail(string tomail, string KA, string SF)
        {
            SmtpClient smtpclient = new SmtpClient();

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            smtpclient.Port = 587;

            //const string username = "******";
            //const string password = "******";
            //MailAddress fromaddress = new MailAddress("*****@*****.**");
            //smtpclient.Host = "smtp.yandex.com";
            //mail.To.Add("*****@*****.**");


            const string username    = "******";
            const string password    = "******";
            MailAddress  fromaddress = new MailAddress("*****@*****.**");

            smtpclient.Host = "mail.yandex.net";
            mail.To.Add(tomail);


            mail.From = fromaddress;

            mail.Subject = "ŞİFRE HATIRLATMA";

            mail.IsBodyHtml = true;


            string mailicerik = "Sisteme giriş yaparken kullandığınız kullanıcı adı ve şifre aşağıdadır.<br>" +
                                Environment.NewLine +
                                Environment.NewLine + "<br>Kullanıcı Adı:  " + KA +
                                Environment.NewLine + "<br>Şifre:  " + SF;



            ContentType mimeType = new System.Net.Mime.ContentType("text/html");


            AlternateView alternate = AlternateView.CreateAlternateViewFromString(mailicerik, mimeType);

            mail.AlternateViews.Add(alternate);
            smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpclient.Credentials    = new System.Net.NetworkCredential(username, password);
            smtpclient.EnableSsl      = true;
            try
            {
                smtpclient.Send(mail);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #54
0
        internal void SetContentFromString(string contentString, Encoding encoding, string mediaType)
        {
            if (contentString == null)
            {
                throw new ArgumentNullException("content");
            }
            if (this.part.Stream != null)
            {
                this.part.Stream.Close();
            }
            if ((mediaType == null) || (mediaType == string.Empty))
            {
                mediaType = "text/plain";
            }
            int offset = 0;

            try
            {
                if (((MailBnfHelper.ReadToken(mediaType, ref offset, null).Length == 0) || (offset >= mediaType.Length)) || (mediaType[offset++] != '/'))
                {
                    throw new ArgumentException(SR.GetString("MediaTypeInvalid"), "mediaType");
                }
                if ((MailBnfHelper.ReadToken(mediaType, ref offset, null).Length == 0) || (offset < mediaType.Length))
                {
                    throw new ArgumentException(SR.GetString("MediaTypeInvalid"), "mediaType");
                }
            }
            catch (FormatException)
            {
                throw new ArgumentException(SR.GetString("MediaTypeInvalid"), "mediaType");
            }
            System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType(mediaType);
            if (encoding == null)
            {
                if (MimeBasePart.IsAscii(contentString, false))
                {
                    encoding = Encoding.ASCII;
                }
                else
                {
                    encoding = Encoding.GetEncoding("utf-8");
                }
            }
            contentType.CharSet = encoding.BodyName;
            byte[] bytes = encoding.GetBytes(contentString);
            this.part.SetContent(new MemoryStream(bytes), contentType);
            if (MimeBasePart.ShouldUseBase64Encoding(encoding))
            {
                this.part.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            }
            else
            {
                this.part.TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable;
            }
        }
    public static MailMessage CreateMeetingRequest(DateTime dtStart, string Duration, DateTime dtEnd, string strSubject, string strSummary, string strLocation, string strMeetWith, string strOrganizerName, string strOrganizerEmail, MailAddressCollection macAttendeeList)
    {
        //Create an instance of mail message
        MailMessage mmMessage = new MailMessage();

        //  Set up the different mime types contained in the message
        //System.Net.Mime.ContentType typeText = new System.Net.Mime.ContentType("text/plain");
        System.Net.Mime.ContentType typeHTML     = new System.Net.Mime.ContentType("text/html");
        System.Net.Mime.ContentType typeCalendar = new System.Net.Mime.ContentType("text/calendar");

        //  Add parameters to the calendar header
        typeCalendar.Parameters.Add("method", "REQUEST");
        typeCalendar.Parameters.Add("name", "meeting.ics");

        ////  Create message body parts in text format
        //string strBodyText = "Type:Meeting\r\nOrganizer: {0}\r\nStart Time:{1}\r\nEnd Time:{2}\r\nTime Zone:{3}\r\nLocation: {4}\r\n\r\n*~*~*~*~*~*~*~*~*~*\r\n\r\n{5}";
        //strBodyText = string.Format(strBodyText, strOrganizerName, dtStart.ToLongDateString() + " " + dtStart.ToLongTimeString(),
        //dtEnd.ToLongDateString() + " " + dtEnd.ToLongTimeString(), System.TimeZone.CurrentTimeZone.StandardName,
        //strLocation, strSummary);
        //AlternateView viewText = AlternateView.CreateAlternateViewFromString(strBodyText, typeText);
        //mmMessage.AlternateViews.Add(viewText);

        //Create the Body in HTML format
        string strBodyHTML = "<HTML>\r\n<HEAD>\r\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=utf-8\">\r\n<TITLE>{0}</TITLE>\r\n</HEAD>\r\n<BODY>\r\n<P><FONT SIZE=2>Type:Meeting<BR>\r\nOrganizer:{1}<BR>\r\nStart Time:{2}<BR>\r\nDuration:{3}<BR>\r\nEnd Time:{4}<BR>\r\nTime Zone:{5}<BR>\r\nMeeting With:{6}<BR>\r\n<BR>\r\n*~*~*~*~*~*~*~*~*~*<BR>\r\n<BR>\r\n{7}<BR>\r\n</FONT>\r\n</P>\r\n\r\n</BODY>\r\n</HTML>";

        strBodyHTML = string.Format(strBodyHTML, strSummary, strOrganizerName, dtStart.ToLongDateString() + " " + dtStart.ToLongTimeString(), Duration,
                                    dtEnd.ToLongDateString() + " " + dtEnd.ToLongTimeString(), System.TimeZone.CurrentTimeZone.StandardName,
                                    strMeetWith, strSummary);
        AlternateView viewHTML = AlternateView.CreateAlternateViewFromString(strBodyHTML, typeHTML);

        mmMessage.AlternateViews.Add(viewHTML);

        //Create the Body in VCALENDAR format
        string strCalDateFormat = "yyyyMMddTHHmmssZ";
        string strBodyCalendar  = "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nPRODID:Microsoft CDO for Microsoft Exchange\r\nVERSION:2.0\r\nBEGIN:VTIMEZONE\r\nTZID:(GMT-06.00) Central Time (US &amp; Canada)\r\nX-MICROSOFT-CDO-TZID:11\r\nBEGIN:STANDARD\r\nDTSTART:16010101T020000\r\nTZOFFSETFROM:-0500\r\nTZOFFSETTO:-0600\r\nRRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=11;BYDAY=1SU\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16010101T020000\r\nTZOFFSETFROM:-0600\r\nTZOFFSETTO:-0500\r\nRRULE:FREQ=YEARLY;WKST=MO;INTERVAL=1;BYMONTH=3;BYDAY=2SU\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nDTSTAMP:{8}\r\nDTSTART:{0}\r\nSUMMARY:{7}\r\nUID:{5}\r\nATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=\"{9}\":MAILTO:{9}\r\nACTION;RSVP=TRUE;CN=\"{4}\":MAILTO:{4}\r\nORGANIZER;CN=\"{3}\":mailto:{4}\r\nLOCATION:{2}\r\nDTEND:{1}\r\nDESCRIPTION:{7}\\N\r\nSEQUENCE:1\r\nPRIORITY:5\r\nCLASS:\r\nCREATED:{8}\r\nLAST-MODIFIED:{8}\r\nSTATUS:CONFIRMED\r\nTRANSP:OPAQUE\r\nX-MICROSOFT-CDO-BUSYSTATUS:BUSY\r\nX-MICROSOFT-CDO-INSTTYPE:0\r\nX-MICROSOFT-CDO-INTENDEDSTATUS:BUSY\r\nX-MICROSOFT-CDO-ALLDAYEVENT:FALSE\r\nX-MICROSOFT-CDO-IMPORTANCE:1\r\nX-MICROSOFT-CDO-OWNERAPPTID:-1\r\nX-MICROSOFT-CDO-ATTENDEE-CRITICAL-CHANGE:{8}\r\nX-MICROSOFT-CDO-OWNER-CRITICAL-CHANGE:{8}\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:REMINDER\r\nTRIGGER;RELATED=START:-PT00H15M00S\r\nEND:VALARM\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";

        strBodyCalendar = string.Format(strBodyCalendar, dtStart.ToUniversalTime().ToString(strCalDateFormat), dtEnd.ToUniversalTime().ToString(strCalDateFormat),
                                        strLocation, strOrganizerName, strOrganizerEmail, Guid.NewGuid().ToString("B"), strSummary, strSubject,
                                        DateTime.Now.ToUniversalTime().ToString(strCalDateFormat), macAttendeeList.ToString());
        AlternateView viewCalendar = AlternateView.CreateAlternateViewFromString(strBodyCalendar, typeCalendar);

        viewCalendar.TransferEncoding = TransferEncoding.SevenBit;
        mmMessage.AlternateViews.Add(viewCalendar);

        //Adress the message
        mmMessage.From = new MailAddress(strOrganizerEmail);
        foreach (MailAddress attendee in macAttendeeList)
        {
            mmMessage.To.Add(attendee);
        }
        mmMessage.To.Add(strOrganizerEmail);
        mmMessage.Subject = strSubject;

        return(mmMessage);
    }
Example #56
0
        public ActionResult MailOkey(RegisterViewModal data)
        {
            try
            {
                SmtpClient smtpclient            = new SmtpClient();
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                smtpclient.Port      = 587;
                smtpclient.EnableSsl = true;
                const string username    = "******";
                const string password    = "******";
                MailAddress  fromaddress = new MailAddress("*****@*****.**");
                smtpclient.Host = "smtp.gmail.com"; //mail.yesilkasaba.com
                mail.To.Add("*****@*****.**");
                mail.To.Add("*****@*****.**");

                mail.From = fromaddress;

                mail.Subject = ("Yeni Kayıt");

                mail.IsBodyHtml = true;

                string icerik = "";


                icerik += @"<img   align='center' border='0' class='center autowidth' 
                src = 'http://www.sayazilim.com/wp-content/uploads/2018/02/SA-YAZILIM-LOGO.png'
                style = 'text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; text-align:center; width: 10%; max-width: 250px; display: block;' /> ";
                icerik += "<br /><br /><b><font color=#b03060>Firma Bilgileri</font></b><br />";
                icerik += "<br /><b>Firma Adı : </b>" + data.FirmaIsmi;
                icerik += "<br /><b>Firma Mail Adresi : </b>" + data.Email;
                icerik += "<br /><b>Firma Tel : </b>" + data.FirmaTel;
                icerik += "<br /><b>Açıklama : </b>" + data.Aciklama;



                ContentType mimeType = new System.Net.Mime.ContentType("text/html");


                AlternateView alternate = AlternateView.CreateAlternateViewFromString(icerik, mimeType);
                mail.AlternateViews.Add(alternate);
                smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpclient.Credentials    = new System.Net.NetworkCredential(username, password);
                smtpclient.EnableSsl      = true;

                ViewBag.message = "Kaydınız Başarıyla Oluşturulmuştur.";

                smtpclient.Send(mail);
                return(Json(new { success = true, Message = "Mail Gönderildi" }));
            }
            catch (Exception E1)
            {
                System.IO.File.WriteAllText(Path.Combine(@"C: \Users\Alperen\AppData\Local\Sayazilim", "sonuc.xml"), E1.ToString());
                return(Json(new { success = false, Message = "Mail Gönderilemedi" }));
            }
        }
Example #57
0
        //</snippet4>

        //<snippet5>
        public static void CreateMessageWithMultipleViews(string server, string recipients)
        {
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
                "*****@*****.**",
                recipients,
                "This email message has multiple views.",
                "This is some plain text.");

            // Construct the alternate body as HTML.
            string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";

            body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
            body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
            body += "</FONT></DIV></BODY></HTML>";

            ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            // Add the alternate body to the message.

            AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);

            message.AlternateViews.Add(alternate);

            // Send the message.
            SmtpClient client = new SmtpClient(server);

            client.Credentials = CredentialCache.DefaultNetworkCredentials;

            try
            {
                client.Send(message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateMessageWithMultipleViews(): {0}",
                                  ex.ToString());
            }
            // Display the values in the ContentType for the attachment.
            ContentType c = alternate.ContentType;

            Console.WriteLine("Content type");
            Console.WriteLine(c.ToString());
            Console.WriteLine("Boundary {0}", c.Boundary);
            Console.WriteLine("CharSet {0}", c.CharSet);
            Console.WriteLine("MediaType {0}", c.MediaType);
            Console.WriteLine("Name {0}", c.Name);
            Console.WriteLine("Parameters: {0}", c.Parameters.Count);
            foreach (DictionaryEntry d in c.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            Console.WriteLine();
            alternate.Dispose();
        }
Example #58
0
        public static void SendMail(string recipient, string subject, string message)
        {
            SmtpClient client = new SmtpClient("smtp-mail.outlook.com");

            string _sender   = "*****@*****.**";
            string _password = "******";

            client.Port                  = 587;
            client.DeliveryMethod        = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            System.Net.NetworkCredential credentials =
                new System.Net.NetworkCredential(_sender, _password);
            client.EnableSsl   = true;
            client.Credentials = credentials;

            try
            {
                MailMessage mail = new MailMessage();
                mail.Subject = subject;
                mail.Body    = message;
                mail.From    = new MailAddress(_sender);

                if (!string.IsNullOrEmpty(recipient))
                {
                    string[] addressToSplit = recipient.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    try
                    {
                        foreach (string add in addressToSplit)
                        {
                            mail.To.Add(add);
                        }
                    }
                    catch (FormatException)
                    {
                        throw new Exception(string.Format("Incorrect \"To\" email address to format [{0}]", mail));
                    }
                }

                ContentType mimeType = null;
                mimeType         = new System.Net.Mime.ContentType("text/html");
                mimeType.CharSet = "UTF-8";
                AlternateView alternate = AlternateView.CreateAlternateViewFromString(message, mimeType);

                mail.AlternateViews.Add(alternate);

                client.Send(mail);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
        public void SendResetPasswordEmail(string memberEmail, string resetGUID)
        {
            //Send a reset email to member
            // Create the email object first, then add the properties.
            var myMessage = new MailMessage(EmailFromAddress, memberEmail);

            //Subject
            myMessage.Subject = "Reset your password";

            myMessage.IsBodyHtml = true;

            //Reset link
            string baseURL  = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty);
            var    resetURL = baseURL + Constants.UrlResetPassword + "?resetGUID=" + resetGUID;

            //HTML Message
            string body = string.Format(
                "<h3>Reset Your Password</h3>" +
                "<p>You have requested to reset your password<br/>" +
                "If you have not requested to reset your password, simply ignore this email and delete it</p>" +
                "<p><a href='{0}'>Reset your password</a></p>",
                resetURL);

            myMessage.Body = body;

            //PlainText Message
            ContentType mimeType = new System.Net.Mime.ContentType("text/html");
            // Add the alternate body to the message.

            AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);

            myMessage.AlternateViews.Add(alternate);

            //// Create an SMTP transport for sending email.
            //var transportSMTP = new SmtpClient();

            //// Send the email.
            //transportSMTP.Send(myMessage);

            //ToDo: used this as above 2 lines caused
            //
            //'Service not available, closing transmission channel.
            //The server response was: Timeout waiting for data from client.'
            //
            using (var transportSMTP = new SmtpClient()
            {
                EnableSsl = true
            })
            {
                transportSMTP.Send(myMessage);
            }
        }
Example #60
0
        /// <summary>Creates a <see cref="T:System.Net.Mail.LinkedResource" /> object from a string to be included in an email attachment as an embedded resource, with the specified content type, and media type as plain text.</summary>
        /// <returns>A <see cref="T:System.Net.Mail.LinkedResource" /> object that contains the embedded resource to be included in the email attachment.</returns>
        /// <param name="content">A string that contains the embedded resource to be included in the email attachment.</param>
        /// <param name="contentType">The type of the content.</param>
        /// <exception cref="T:System.ArgumentNullException">The specified content string is null.</exception>
        public static LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType)
        {
            if (content == null)
            {
                throw new ArgumentNullException();
            }
            MemoryStream contentStream = new MemoryStream(Encoding.Default.GetBytes(content));

            return(new LinkedResource(contentStream, contentType)
            {
                TransferEncoding = System.Net.Mime.TransferEncoding.QuotedPrintable
            });
        }