private static async Task <byte[]> ToByteArrayAsync(this FormFile formFile) { using (MemoryStream ms = new MemoryStream()) { await formFile.CopyToAsync(ms); return(ms.ToArray()); } }
public IActionResult TestUpload(FormFile FileUpload) { using (var stream = System.IO.File.Create("C:\\Users\\stefa\\aaa.jpg")) { FileUpload.CopyToAsync(stream); } return(View()); }
//Запись информации с помощью файла public async Task <IActionResult> OnPostUploadAsync() { if (FormFile != null && FormFile?.Length > 0 && (FormFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || FormFile.ContentType == "text/plain")) { try { //.docx if (FormFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") { using (var memoryStream = new MemoryStream()) { await FormFile.CopyToAsync(memoryStream); using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStream, true)) { var body = doc.MainDocumentPart.Document.Body; original = body.InnerText; } } model = new EncryptModel(original, ToEncrypt, Key); Key = ""; } else // .txt { using (var memoryStream = new MemoryStream()) { await FormFile.CopyToAsync(memoryStream); if (memoryStream.Length < 2097152) { original = Encoding.UTF8.GetString(memoryStream.ToArray()); } else { ModelState.AddModelError("File", "The file is too large."); } } model = new EncryptModel(original, ToEncrypt, Key); Key = ""; } } catch (Exception e) { ModelState.AddModelError("File", "ИСКЛЮЧЕНИЕ:" + e.Message.ToString()); return(Page()); } } else { ModelState.AddModelError("File", "Choose file bliiin!!"); } return(Page()); }
public async Task <IActionResult> Post(List <IFormFile> files) { long sizes = files.Sum(f => f.Length); var filepath = Path.GetTempFileName(); int i = 1; string contents = ""; foreach (var FormFile in files) { //step 1: before pass the file, check the file content type if (FormFile.ContentType.ToLower() != "text/plain") { return(BadRequest("The " + Path.GetFileName(filepath) + "is not a text file! Please upload a correct text file")); } //step 2: chech whether the file is empty anot else if (FormFile.Length <= 0) { return(BadRequest("The " + Path.GetFileName(filepath) + "is empty!")); } //step 3: check file size got over limit anot else if (FormFile.Length > 1048576) //more than 1MB { return(BadRequest("The " + Path.GetFileName(filepath) + "is too big!")); } //step 4: start to transfer the file to the correct destination else { //e.g file path var filedest = "file path" + i + ".txt"; using (var stream = new FileStream(filedest, FileMode.Create)) { await FormFile.CopyToAsync(stream); } //read file using (var reader = new StreamReader(FormFile.OpenReadStream())) { contents = contents + "\\n" + await reader.ReadToEndAsync(); } } } TempData["message"] = "Success Transfer" + contents; return(RedirectToAction("Index")); }
public static async Task <string> Save(this Byte[] file, string root, string MainFolder, string Subfolder) { var NewName = Guid.NewGuid().ToString() + ".png"; var fullpath = Path.Combine(root, MainFolder, Subfolder, NewName); var stream = new MemoryStream(file); IFormFile Formfile = new FormFile(stream, 0, file.Length, NewName, "fileName"); using (var data = new FileStream(fullpath, FileMode.Create)) { await Formfile.CopyToAsync(data); } return(NewName); }
public async Task SubirArchivoAsync(FormFile Archivo) { long size = Archivo.Length; if (size > 0) { var filePath = Path.GetTempFileName(); using (var stream = System.IO.File.Create(filePath)) { await Archivo.CopyToAsync(stream); } } // Process uploaded files // Don't rely on or trust the FileName property without validation. }
private async Task <string> postUploadImage(byte[] imageArray) { string rutaFoto = string.Empty; if (imageArray != null && imageArray.Length > 0) { var streamRemote = new MemoryStream(imageArray); var guid = Guid.NewGuid().ToString(); var guid2 = Guid.NewGuid().ToString(); var file = string.Format("{0}.pdf", guid + guid2); var folder = "/Reports"; //rutaFoto= string.Format("{0}/{1}",folder,file); /// var folder_fotos = "/Fotos"; rutaFoto = string.Format("{0}/{1}", folder, file); string pathExist = _hostingEnvironment.WebRootPath + folder;// _hostingEnvironment.WebRootPath es Igual a "wwwroot" if (!Directory.Exists(pathExist)) { Directory.CreateDirectory(pathExist); //string message="No existe el directorio, se creo"; } else { //string message="Si existe el directorio"; } var formFile = new FormFile(streamRemote, 0, streamRemote.Length, "name", file); if (formFile == null || formFile.Length == 0) { return("file not selected"); } var path = Path.Combine( Directory.GetCurrentDirectory(), pathExist, Path.GetFileName(formFile.FileName)); //Ruta foto //var fullPath = string.Format("{0}", path); //foto.Ruta= rutaFoto; using (var stream = new FileStream(path, FileMode.Create)) { await formFile.CopyToAsync(stream); } } return(rutaFoto); }
public static async Task <bool> SaveEnterImgAsync(FormFile imageFile, string fileDir, string filePath) { if (!Directory.Exists(fileDir)) { Directory.CreateDirectory(fileDir); } try { using (var stream = new FileStream(filePath, FileMode.Create)) { await imageFile.CopyToAsync(stream); } return(true); } catch (Exception e) { } return(false); }
public async Task <string> Upload_Image(FormFile file, string name) { var newFileName = string.Empty; if (file.Length > 0) { var fileName = string.Empty; string PathDB = string.Empty; //Getting FileName fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); //Assigning Unique Filename (Guid) var myUniqueFileName = Convert.ToString(Guid.NewGuid()); //Getting file Extension var FileExtension = Path.GetExtension(fileName); // concating FileName + FileExtension newFileName = myUniqueFileName + FileExtension; _env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), name); // Combines two strings into a path. fileName = _env.WebRootPath + '\\' + newFileName; // if you want to store path of folder in database PathDB = name + "/" + newFileName; newFileName = PathDB; using (FileStream fs = System.IO.File.Create(fileName)) { await file.CopyToAsync(fs); fs.Flush(); } } return(newFileName); }
public override async Task Upload() { using (var memoryStream = new MemoryStream()) { await FormFile.CopyToAsync(memoryStream); Image image = Image.FromStream(memoryStream); if (image.Width > MaxWidth || image.Height > MaxHeight) { double scale = Math.Min(MaxWidth / (double)image.Width, MaxHeight / (double)image.Height); int newWidth = (int)(image.Width * scale); int newHeight = (int)(image.Height * scale); Bitmap newImage = new Bitmap(newWidth, newHeight); using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(image, 0, 0, newWidth, newHeight); } image = newImage; } var images = new List <(Image, string fileName)>(); images.Add((image, Name + "." + Extension)); if (HasThumbnail) { images.Add((GenerateThumbnail(image), Name + "-thumb." + Extension)); } Save(images, Directory, format, quality); } }
public static async System.Threading.Tasks.Task CheckMailAsync()//string toemail, string username, string password) { try { MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "pachikkara", EAGetMail.ServerProtocol.Imap4); // Enable SSL connection. oServer.SSLConnection = true; // Set 993 SSL port oServer.Port = 993; MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); MongoDbRepository <MailInvoice> mi = new MongoDbRepository <MailInvoice>();// retrieve unread/new email only oClient.GetMailInfosParam.Reset(); oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly; //oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.; MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Receive email from IMAP4 server Mail oMail = oClient.GetMail(info); if (oMail.Attachments.Length > 0) { foreach (var attachment in oMail.Attachments) { if (attachment.ContentType == "application/json") { var stream = new MemoryStream(attachment.Content); IFormFile file = new FormFile(stream, 0, attachment.Content.Length, "name", "Invoice.json"); // var filePath = Path.GetTempFileName(); var filePath = Path.GetTempFileName(); using (var streamfile = System.IO.File.Create(filePath)) { await file.CopyToAsync(streamfile); } //File.WriteAllBytes(filePath, attachment.Content); //using (var streamcreate = System.IO.File.Create(filePath)) //{ //} //StreamReader streamReader = new StreamReader(new MemoryStream(attachment.Content));// Server.MapPath("~/FileUpload/" + Path.GetFileName(file.FileName))); // string data = streamReader.ReadToEnd(); IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001"); var result = ipfs.FileSystem.AddFileAsync(filePath).Result; var url = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + "Invoice.json"; using (StreamReader r = new StreamReader(new MemoryStream(attachment.Content))) { var json = r.ReadToEnd(); var invoiceJSON = JsonConvert.DeserializeObject <InvoiceJSON>(json); MailInvoice mailInvoice = new MailInvoice(); mailInvoice.ToEmail = oMail.From.Address; mailInvoice.invoiceJSON = invoiceJSON; mailInvoice.CreatedOn = DateTime.Now; mailInvoice.InvoiceStatus = MailInvoiceStatus.Created; mailInvoice.IsSend = false; mailInvoice.HashUrl = url; mailInvoice.mailInvoiceCreationType = MailInvoiceCreationType.Received; mi.Insert(mailInvoice); } } } } Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); if (!info.Read) { oClient.MarkAsRead(info, true); } } // Quit and expunge emails marked as deleted from IMAP4 server. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine(ep.Message); } }
public async Task <IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } bool cvUploaded = (FormFile != null); byte[] Content = new byte[0]; if (cvUploaded) { using (var memoryStream = new MemoryStream()) { await FormFile.CopyToAsync(memoryStream); if (memoryStream.Length < 2097152 * 4) { Content = memoryStream.ToArray(); } else { ModelState.AddModelError("File", "The file is too large."); } } } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } if (cvUploaded) { CV cv = new CV(); cv.Title = FormFile.FileName; cv.Content = Content; cv.Extension = Path.GetExtension(FormFile.FileName); if (cv.Extension.Length > 20) { cv.Extension = "unknown"; } ((Candidate)user).CV = cv; var updt = await _userManager.UpdateAsync(user); if (!updt.Succeeded) { StatusMessage = "Unexpected error when trying to update educations."; return(RedirectToPage()); } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your profile has been updated"; } return(RedirectToPage()); }
// To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. public async Task <IActionResult> OnPostAsync(string?languagePick, string?publisherPick, string?deleteLanguage, string?deletePublisher, string?deleteAuthor, string?authorPick, List <int>?hiddenAuthorsList, string?final, string?picturePick, string?deletePicture) { if (!string.IsNullOrEmpty(languagePick) && "pick".Equals(languagePick)) { LanguageIsSet = true; Book.LanguageId = PickLanguageModel.LanguageId; Book.Language = _context.Languages.Find(Book.LanguageId); } else if (!string.IsNullOrEmpty(languagePick) && "add".Equals(languagePick) && !string.IsNullOrEmpty(PickLanguageModel.NewLanguageName)) { LanguageIsSet = true; var language = new Language(PickLanguageModel.NewLanguageName, "EE"); if (!_context.Languages.Any(l => l.LanguageName == language.LanguageName)) { _context.Languages.Add(language); _context.SaveChanges(); Book.LanguageId = language.LanguageId; } else { Book.LanguageId = _context.Languages .First(l => l.LanguageName == language.LanguageName).LanguageId; } Book.Language = _context.Languages.Find(Book.LanguageId); } if (!string.IsNullOrEmpty(deleteLanguage)) { Book.LanguageId = 0; LanguageIsSet = false; } if (!string.IsNullOrEmpty(publisherPick) && "pick".Equals(publisherPick) && PickPublisherModel.PublisherId != null) { PublisherIsSet = true; Book.PublisherId = (int)PickPublisherModel.PublisherId; Book.Publisher = _context.Publishers.Find(Book.PublisherId); } else if (!string.IsNullOrEmpty(publisherPick) && "add".Equals(publisherPick) && !string.IsNullOrEmpty(PickPublisherModel.NewPublisherName)) { PublisherIsSet = true; var publisher = new Publisher(PickPublisherModel.NewPublisherName); if (!_context.Publishers.Any(a => a.PublisherName == publisher.PublisherName)) { _context.Publishers.Add(publisher); _context.SaveChanges(); Book.PublisherId = publisher.PublisherId; } else { Book.PublisherId = _context.Publishers .First(p => p.PublisherName == publisher.PublisherName).PublisherId; } Book.Publisher = _context.Publishers.Find(Book.PublisherId); } if (!string.IsNullOrEmpty(deletePublisher)) { Book.PublisherId = 0; PublisherIsSet = false; } if (LanguageIsSet) { Book.Language = _context.Languages.Find(Book.LanguageId); } else { PickLanguageModel.LanguagesSelectlist = new SelectList(_context.Languages, nameof(Language.LanguageId), nameof(Language.LanguageName)); } if (PublisherIsSet) { Book.Publisher = _context.Publishers.Find(Book.PublisherId); } else { PickPublisherModel.PublishersSelectlist = new SelectList(_context.Publishers, nameof(Publisher.PublisherId), nameof(Publisher.PublisherName)); } AuthorIds = hiddenAuthorsList; if (!string.IsNullOrEmpty(authorPick) && "pick".Equals(authorPick)) { Console.WriteLine("Got to Pick!" + SelectedAuthorIds.Count + PickAuthorPartialModel.SelectedAuthorIds.Count); foreach (var selectedAuthorId in PickAuthorPartialModel.SelectedAuthorIds) { if (!AuthorIds.Contains(selectedAuthorId)) { AuthorIds.Add(selectedAuthorId); } } } var author = PickAuthorPartialModel.Author; if (!string.IsNullOrEmpty(authorPick) && "add".Equals(authorPick) && !string.IsNullOrEmpty(author.FirstName) && !string.IsNullOrEmpty(author.LastName)) { Console.WriteLine(author); if (!_context.Authors.Any(a => a.FirstName == author.FirstName && a.LastName == author.LastName && a.BirthYear == author.BirthYear && a.DeathYear == author.DeathYear && a.Description == author.Description)) { Console.WriteLine("Got to add author!"); _context.Authors.Add(author); _context.SaveChanges(); AuthorIds.Add(author.AuthorId); } else { AuthorIds.Add(_context.Authors.FirstOrDefault(a => a.FirstName == author.FirstName && a.LastName == author.LastName && a.BirthYear == author.BirthYear && a.DeathYear == author.DeathYear && a.Description == author.Description).AuthorId); } } if (!string.IsNullOrEmpty(deleteAuthor) && int.TryParse(deleteAuthor, out var authorId)) { Console.WriteLine("AuhorInt: " + authorId); AuthorIds.Remove(authorId); } BookAuthorsSelectList = new SelectList(_context.Authors, nameof(Author.AuthorId), nameof(Author.FirstName)); PickAuthorPartialModel.BookAuthorsSelectList = new SelectList(_context.Authors, nameof(Author.AuthorId), nameof(Author.FirstName)); Authors = _context.Authors.Where(a => AuthorIds.Contains(a.AuthorId)) .Select(a => new AuthorDto() { Author = a, BooksAuthored = a.AuthoredBooks.Count }).ToList(); Console.WriteLine("Before picturepick!"); if (!string.IsNullOrEmpty(picturePick) && "add".Equals(picturePick) && FormFile != null) { Console.WriteLine("Inside picturePick! " + FormFile.FileName); var file = Path.Combine(_env.WebRootPath, "resources", FormFile.FileName); using (var fileStream = new FileStream(file, FileMode.Create)) { await FormFile.CopyToAsync(fileStream); } UploadImagePath = FormFile.FileName; Book.PicturePath = UploadImagePath; } if (!string.IsNullOrEmpty(deletePicture) && "remove".Equals(deletePicture)) { UploadImagePath = null; Book.PicturePath = null; } Book.PicturePath = UploadImagePath; if (!string.IsNullOrEmpty(final) && "Create".Equals(final) && !string.IsNullOrEmpty(Book.Title) && Book.Language != null && Book.Publisher != null && AuthorIds.Count > 0 && !string.IsNullOrEmpty(Book.PicturePath)) { Book.BookAuthors = AuthorIds.Select(a => new BookAuthor() { AuthorId = a, BookId = Book.BookId }).ToList(); _context.Attach(Book).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BookExists(Book.BookId)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); } return(Page()); /* * if (!ModelState.IsValid) * { * return Page(); * } * * _context.Attach(Domain.Book).State = EntityState.Modified; * * try * { * await _context.SaveChangesAsync(); * } * catch (DbUpdateConcurrencyException) * { * if (!BookExists(Domain.Book.BookId)) * { * return NotFound(); * } * else * { * throw; * } * } * * return RedirectToPage("./Index");*/ }
public static async Task CreateInvoiceWithMailSending(CreateTaxInvoice invoice, string fromEmail, string path, ApplicationUser au) { int counter = 0; try { //var collectionmr = db.GetCollection<MerchantRegistration>("MerchantRegistration"); // var mr = collectionmr.FindAll().ToList<MerchantRegistration>().FirstOrDefault(); InvoiceJSON invoicejson = new InvoiceJSON(); invoicejson.version = "1.0.1118"; billLists[] billListarray = new billLists[1]; billLists billlist = new billLists(); billlist.userGstin = au.GstId; billlist.supplyType = "O"; billlist.subSupplyType = 1; billlist.docType = "INV"; billlist.docNo = "20"; //Test billlist.docDate = invoice.DateIssue; billlist.transType = 1; billlist.fromGstin = invoice.GSTIDSeller; billlist.fromTrdName = invoice.NameoFSeller; //T2 // billlist.fromAddr1 = mr.Address1; // billlist.fromAddr2 = mr.Address2; // billlist.fromPlace = mr.City; billlist.fromStateCode = 27; billlist.actualFromStateCode = 27; //T2 billlist.toGstin = invoice.GSTIdBuyer; billlist.toTrdName = invoice.NameBuyer; billlist.toAddr1 = "1st floor, Jain Complex, opp.Bhoot Nath Mandir, Indra Nagar"; billlist.toAddr2 = ""; billlist.toPlace = "Pune"; billlist.toStateCode = 27; billlist.actualToStateCode = 27; //Test billlist.totalValue = invoice.TotalAmount;// 121.00; billlist.cgstValue = invoice.GSTAmount / 2; billlist.sgstValue = invoice.GSTAmount / 2; billlist.igstValue = 0.00; billlist.cessValue = 0.00; billlist.TotNonAdvolVal = 0.00; billlist.OthValue = 0.0000; billlist.totInvValue = invoice.TotalAmount; billlist.transMode = 1; billlist.transDistance = 60; counter++; billlist.transporterName = ""; billlist.transporterId = ""; billlist.transDocNo = ""; billlist.transDocDate = invoice.DateIssue; billlist.vehicleNo = ""; billlist.vehicleType = "R"; counter++; ItemLists[] itemlistarray = new ItemLists[invoice.itemDetails.Count]; for (int count = 0; count < invoice.itemDetails.Count; count++) { ItemLists itemlist = new ItemLists(); itemlist.itemNo = count + 1; itemlist.productName = invoice.itemDetails[count].Product; itemlist.productDesc = invoice.itemDetails[count].Product; itemlist.quantity = invoice.itemDetails[count].Quantity; //il.qtyUnit = invoice.itemDetails[count].Q; itemlist.qtyUnit = "Qty"; itemlist.taxableAmount = invoice.itemDetails[count].Amount;// (invoice.itemDetails[count].GST / 100) * invoice.itemDetails[count].Amount; itemlist.sgstRate = Convert.ToInt32(itemlist.taxableAmount / 2); itemlist.cgstRate = Convert.ToInt32(itemlist.taxableAmount / 2); itemlist.igstRate = 0; itemlist.cessRate = 0; itemlist.cessNonAdvol = 0; itemlistarray[count] = itemlist; } billlist.itemList = itemlistarray; billListarray[0] = billlist; invoicejson.billLists = billListarray; string json = JsonConvert.SerializeObject(invoicejson, Formatting.Indented); var menstream = new MemoryStream(Encoding.Default.GetBytes(json)); // var filePath = Path.GetTempFileName(); //File.WriteAllBytes(filePath, menstream.ToArray()); var stream = new MemoryStream(Encoding.Default.GetBytes(json)); IFormFile file = new FormFile(stream, 0, (Encoding.Default.GetBytes(json)).Length, "name", "Invoice.json"); // var filePath = Path.GetTempFileName(); var filePath = Path.GetTempFileName(); using (var streamfile = System.IO.File.Create(filePath)) { await file.CopyToAsync(streamfile); } //File.WriteAllBytes(filePath, attachment.Content); //using (var streamcreate = System.IO.File.Create(filePath)) //{ //} //StreamReader streamReader = new StreamReader(new MemoryStream // using (var stream = System.IO.File.Create(filePath)) { //File.WriteAllBytes(filePath, menstream.ToArray()); //await filePath.CopyToAsync(menstream); } StreamReader streamReader = new StreamReader(filePath);// Server.MapPath("~/FileUpload/" + Path.GetFileName(file.FileName))); string data = streamReader.ReadToEnd(); //InvoiceJSON invoiceJSON = JsonConvert.DeserializeObject<InvoiceJSON>(data); IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001"); var result = ipfs.FileSystem.AddFileAsync(filePath).Result; var url = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + "Invoice.json"; MongoDbRepository <MailInvoice> mdr = new MongoDbRepository <MailInvoice>(); MailInvoice mi = new MailInvoice(); mi.invoiceJSON = invoicejson; mi.FromEmail = fromEmail; mi.ToEmail = invoice.EmailBuyer; mi.InvoiceStatus = MailInvoiceStatus.Created; mi.mailInvoiceCreationType = MailInvoiceCreationType.Created; mi.HashUrl = url; // mi.Hash = Hash; mdr.Insert(mi); var id = mi.Id.ToString(); var fromAddress = new MailAddress("*****@*****.**", "From Name"); var toAddress = new MailAddress(invoice.EmailBuyer, "To Name"); counter++; const string fromPassword = "******"; const string subject = "Invoice"; ///const string body = "Body"; Attachment attachment = new Attachment(menstream, new ContentType("application/json")); attachment.ContentDisposition.FileName = "Invoice.json"; // attachment.ContentType= "application/json"; //mailMessage.Attachments.Add(attachment); string authorityAccept = "http://" + path + "/TaxInvoice/Accept?id=" + id; string authorityReject = "http://" + path + "/TaxInvoice/Reject?id=" + id; //string a1= "<html>You have received an Invoice. Please do check the invoice and conform <a href=\'"; var html = "<html> You have received an Invoice. Please do check the invoice and conform<br /><a href='" + authorityAccept + "' style= \"background-color: #90EE90\" > Accept </a>   <a href='" + authorityReject + "' style= \"background-color: #FFFF00\" > Reject </a></ html >"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = html, IsBodyHtml = true }) { message.Attachments.Add(attachment); smtp.Send(message); } // return invoicejson; } catch (Exception e) { // return invoicejson; } }