How to send an Email in a separate thread? - multithreading

I was sending emails from my website fine, but Email part was slow,
so I have decided to try and put this in a new thread,
And came up with this
public bool sendmail()
{
Thread T1 = new Thread(delegate()
{
MailMessage eMail = new MailMessage();
SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
string EmailFromGCBS = (ConfigurationManager.AppSettings["EmailFROM"]);
eMail.From = new MailAddress(EmailFromGCBS);
eMail.To.Add(new MailAddress(emailTo));
eMail.Subject = emailSubject;
eMail.IsBodyHtml = isHtml;
eMail.Body = emailBody;
smtpClient.Send(eMail);
});
T1.Start();
return true;
}
the thread runs, but there is no emails sent any idea why this is?

Related

display data dynamically on a razor page

There's a console app that uses async method for web site scraping.
using Microsoft.AspNetCore.Authentication;
using HtmlAgilityPack;
using System.Net;
class Program
{
static void Main(string[] args)
{
submainAsync();
Console.ReadKey();
}
private static async Task<bool> submainAsync()
{
ADManager adManager = new ADManager();
List<Person> people;
people = adManager.GetPeopleByPath("ls.local");
string cookie = "0123456789";
if (cookie == String.Empty)
{
Console.WriteLine("check your password");
return false;
}
var peopleAS = getPIDsAsync(people, cookie);
int total = people.Count;
await foreach (Person prs in peopleAS)
{
Console.WriteLine("next is {0} countdown {1}", prs.samAccountName, total--);
}
return true;
}
static private async IAsyncEnumerable<Person> getPIDsAsync(List<Person> people, string inCookie)
{
foreach (Person prs in people)
{
var baseAddress = new Uri("http://192.168.1.100");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
string request = "/doc/admin/directories.asp?act=test&id=META&login=" + prs.samAccountName + "&s=DEFAULT";
var message = new HttpRequestMessage(HttpMethod.Get, request);
message.Headers.Add("Cookie", "t%5FDEFAULT%5Fadmin="+ inCookie);
var result = await client.SendAsync(message);
var resultString = await result.Content.ReadAsStringAsync();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(resultString);
var node = doc.DocumentNode.SelectSingleNode("//*[#id=\"value\"]");
var val = node.InnerText;
prs.PID = node.InnerText;
}
yield return prs;
}
}
}
[ yield return, await foreach ] writelines out data nicely as soon as the next piece of data is ready. Now, I moved the code from a console app to a razor page app, so submainAsync() is called from OnPost. The question is - how can I display scraped data in a table on a razor page? My goal is to display the data dynamically, as soon as the next piece is ready, just like it happens in the Console.
Would someone please point me in the right direction?

How to send a mail notification using C# code

I have used the below code to send the mail notifications using the C# code
public static void SendNotification(string filepath)
{
try
{
SmtpClient mailServer = new SmtpClient(ConfigurationManager.AppSettings["host"], int.Parse(ConfigurationManager.AppSettings["portnumber"]));
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["sender_username"], ConfigurationManager.AppSettings["sender_password"]);
string from = ConfigurationManager.AppSettings["sender"];
string to = ConfigurationManager.AppSettings["receipients"];
string cc = ConfigurationManager.AppSettings["receipientCC"];
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Branch API Export Results";
msg.Body = "Test Mail. Please Find Attached for the Results from Branch API Export";
msg.CC.Add(cc);
msg.Attachments.Add(new Attachment(filepath));
mailServer.Send(msg);
}
catch (Exception ex)
{
//Log
}
}
Included the configuration values in the App.Config. Any better way other than this.
Here is.
private static void SendMail(string subject, string content)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("YOURMAİL");
mail.To.Add("MAİLTO");
mail.Subject = subject;
mail.Body = content;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("YOURMAİL", "YOURMAİLPASSWORD");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
}
}
This is simplest way to send mail. Don't forget to add using System.Net.Mail;

sending mail through controller (using gmail)

So, first time attempting to send mail from a mvc application and lo and behold, it didn't work :(
Here's the spaghetti I've whipped up so far from some sources, needless to say I end up in the Error View:
[HttpPost]
public ActionResult Contact(Contact c)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(c.Email.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myaddress#mail.com");
msg.Subject = "New Message";
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("myaddress#mail.com", "mypassword");
sb.Append("Name: " + c.Name);
sb.Append(Environment.NewLine);
sb.Append("Email: " + c.Email);
sb.Append(Environment.NewLine);
sb.Append("Message: " + c.Message);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View();
}
catch (Exception)
{
return View("Error");
}
}
return View();
}

Inconsistent Template Matching

I'm using the CreateEnvelope() method of the SOAP API to upload a document to DocuSign in the Draft status. When I do this and then request a Sender Token to start an Embedded Sending session, I'm immediately prompted to apply a matching template when the DocuSign interface appears.
If I don't start an Embedded Sending session, however, and the user instead logs into the DocuSign console and opens the Draft envelope, they are NOT automatically prompted to apply the matching template. They have to manually press the "Try automatic template matching on all documents" button, at which point the same template that would've been found automatically in the Embeddded Sending session is found. Is there a reason for this discrepancy?
bool retVal = true;
DocuSignService.DocuSignWS.Envelope envelope = new DocuSignService.DocuSignWS.Envelope();
if (credentials == null)
{
error = ErrorCode.NO_CREDENTIALS;
errorMessage = Strings.GetString("STR_DS_NOCREDS");
return false;
}
envelope.Documents = new DocuSignService.DocuSignWS.Document[itemList.Count];
if (credentials != null)
{
int index = 0;
foreach (Document document in itemList)
{
DocuSignService.DocuSignWS.Document doc = new DocuSignService.DocuSignWS.Document();
doc.ID = document.ID.ToString();
doc.Name = document.Name;
//get document bytes
doc.PDFBytes = document.data;
envelope.Documents[index] = doc;
index++;
}
Tab[] tabs = new DocuSignService.DocuSignWS.Tab[0];
envelope.Tabs = tabs;
envelope.Recipients = new Recipient[0];
//send?
envelope.AccountId = credentials.dsaccountid;
envelope.Subject = "Documents are ready for your signature";
envelope.EmailBlurb = "Documents are awaiting your signature.";
envelope.EnableWetSign = false;
DocuSignService.DocuSignWS.EnvelopeStatus envStatus = new DocuSignService.DocuSignWS.EnvelopeStatus();
using (ServiceWrapper client = new ServiceWrapper())
{
client.UserName = credentials.loginemail;
client.Password = credentials.loginpassword;
client.IntegratorKey = "xxx-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx";
try
{
envStatus = client.CreateEnvelope(envelope);
}
catch (Exception e)
{
ErrorViewerWriter.Write(e);
error = ErrorCode.UPLOADFAILED;
errorMessage = e.Message;
return false;
}
}
}
return retVal;

How to send mail from exchange server without smtp?

I am currently sending mails from my code using smtp, but seems like we will have to migrate to exchange server, is there a difference between the two?
What changes I need to do in my code?
MailMessage loginInfo = new MailMessage();
loginInfo.To.Add("estinationaddress.#ca");
loginInfo.From = new MailAddress("abc#sde.ca");
loginInfo.Subject = "ABC";
loginInfo.Body = "Your username is: " +"abc";
loginInfo.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "www.smtphost.com";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Credentials = new System.Net.NetworkCredential("abc#sde.ca","abc");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(loginInfo);
What changes I will be needing in my code?

Resources