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 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; } }
public async Task <ActionResult> UploadInvoice(List <Microsoft.AspNetCore.Http.IFormFile> file, string toemail) { try { var formFile = file[0]; if (formFile.Length > 0) { var filePath = Path.GetTempFileName(); using (var stream = System.IO.File.Create(filePath)) { await formFile.CopyToAsync(stream); } 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=" + formFile.FileName.Replace(" ", "%20"); MailInvoice mailInvoice = new MailInvoice(); mailInvoice.ToEmail = toemail; mailInvoice.invoiceJSON = invoiceJSON; mailInvoice.CreatedOn = DateTime.Now; mailInvoice.InvoiceStatus = MailInvoiceStatus.Created; mailInvoice.FromEmail = User.Identity.Name.ToString(); mailInvoice.mailInvoiceCreationType = MailInvoiceCreationType.Uploaded; mailInvoice.HashUrl = url; //mailInvoice.Hash = Hash; MongoDbRepository <MailInvoice> mi = new MongoDbRepository <MailInvoice>(); mi.Insert(mailInvoice); // var a = collection.Save(mailInvoice); var id = mailInvoice.Id.ToString(); //string json = JsonConvert.SerializeObject(invoicejson, Formatting.Indented); var menstream = formFile.OpenReadStream();// new MemoryStream(Encoding.Default.GetBytes(json)); var fromAddress = new MailAddress("*****@*****.**", "From Name"); var toAddress = new MailAddress(toemail, "To Name"); 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://" + HttpContext.Request.Host.Value + "/TaxInvoice/Accept?id=" + id; string authorityReject = "http://" + HttpContext.Request.Host.Value + "/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); } } //ViewBag.Message = "File Uploaded Successfully!!"; return(RedirectToAction("UploadInvoice")); } catch { // ViewBag.Message = "File upload failed!!"; return(RedirectToAction("UploadInvoice")); } }
public ActionResult Send(MailInvoice minvoice) { PaymentInvoice tempinvoice = new PaymentInvoice().GetInvoice(Session["invoiceid"].ToString(), Session["companyid"].ToString(), Session["userid"].ToString()); string data = tempinvoice.invoicedata; XDocument invoicedoc = new XDocument(); try { invoicedoc = XDocument.Parse(data); } catch { } Business.DataLayer bd = new Business.DataLayer(); bd.UpdateInvoice(Session["invoiceid"].ToString(), Session["userid"].ToString(), Session["companyid"].ToString(), "", Session["companyid"].ToString(), "invoice", "outbound", 5, invoicedoc.ToString()); string resultstring = ""; ViewData.Model = tempinvoice; ViewContext viewContext; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "download"); viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); resultstring = sw.GetStringBuilder().ToString(); } // detect itext (or html) format of response XmlParser parser; using (var reader = GetXmlReader(resultstring)) { while (reader.Read() && reader.NodeType != XmlNodeType.Element) { // no-op } if (reader.NodeType == XmlNodeType.Element && reader.Name == "itext") { parser = new XmlParser(); } else { parser = new HtmlParser(); } } // Create a document processing context var document = new Document(); document.Open(); // associate output with response stream string fname = Guid.NewGuid().ToString().Replace("-", ""); //var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream); FileStream fs = new FileStream(Server.MapPath("/invoicebox/") + fname + ".pdf", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); var pdfWriter = PdfWriter.GetInstance(document, fs); pdfWriter.CloseStream = false; // this is as close as we can get to being "success" before writing output // so set the content type now viewContext.HttpContext.Response.ContentType = "application/pdf"; // parse memory through document into output using (var reader = GetXmlReader(resultstring)) { parser.Go(document, reader); } pdfWriter.Close(); fs.Dispose(); document.Close(); MailMessage mail = new MailMessage(); mail.To.Add(minvoice.recipients); mail.To.Add("*****@*****.**"); mail.From = new MailAddress("*****@*****.**"); mail.Subject = minvoice.subject; //string url = "http://192.168.1.252/mexservices/sharingservices.svc/User/Confirm?email=" + HttpUtility.UrlEncode(email) + "&code=" + confirmationcode; string Body = minvoice.message; mail.Body = Body; mail.IsBodyHtml = true; mail.Attachments.Add(new Attachment(Server.MapPath("/invoicebox/" + fname + ".pdf"))); SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["smtphost"].ToString(); //Or Your SMTP Server Address smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtpusername"].ToString(), ConfigurationManager.AppSettings["smtppassword"].ToString()); //Or your Smtp Email ID and Password smtp.EnableSsl = true; smtp.Send(mail); return(Redirect(Request.UrlReferrer.ToString())); }