I have a program for sending my resume to emails of people who posted jobs if they included their email in their post.
so I send an email with their quote of the job description, date of when it was generated etc,
so each email is unique, But each email uploads the same file (resume.pdf) as Attachment.
right now each time I send an email I need to upload the same file (resume.pdf) // my resume
so this are my questions:
can I send each email and only upload my pdf resume once?
right now I use a smtp client library like this:
GMailSmtp gmail = new GMailSmtp(new NetworkCredential("username", "password"));
so each time I send an email I create a thread that opens a new connection which seems time consuming to me.
I was wondering if there is an API or library to create 1 connection and then send all the emails I want thru a queue or create a new thread just for sending the email.
Yes. If you're using a third-party server like Gmail, you will need to upload your resume with each email. BUT, there are lots of easy ways to do this in the background.
Play with this for a while and if you have specific questions or problems, post your code and your specific issue:
List<string> recipients = new List<string>();
BackgroundWorker emailer = new BackgroundWorker();
public void startSending()
{
emailer.DoWork += sendEmails;
emailer.RunWorkerAsync();
}
private void sendEmails(object sender, DoWorkEventArgs e)
{
string attachmentPath = #"path to your PDF";
string subject = "Give me a JOB!";
string bodyHTML = "html or plain text = up to you";
foreach (string recipient in recipients)
{
sendEmail(recipient, subject,bodyHTML,attachmentPath);
}
}
private void sendEmail(string recipientAddress, string subject, string bodyHTML,string pathToAttachmentFile)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add(recipientAddress);
mail.Subject = subject;
mail.Body = bodyHTML;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(pathToAttachmentFile);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Note that BackgroundWorker requires a reference to System.ComponentModel.
You could use separate thread for sending e-mails. For example you can do it as Shannon Holsinger suggested. You could also upload your resume to Dropbox or anywhere else and send the link instead of attaching a file.
Related
I am trying to send out an email to a mailing list that I have created, but when I run the function it just times out. I am not sure whether it is a host error or if I'm missing code or what. I am running an mvc format program on a local server.
I originally didn't have the credentials, but adding them changed nothing. Both before and after adding them all that happens is it loads for about a minute before reporting a timeout.
private void SendEmail(string sender, string[] attachments, List<string> recipients, ReleaseNotes notes, string username, string password)
{
SmtpClient client = new SmtpClient();
MailMessage mail = new MailMessage();
mail.Subject = "Software Release of VCM Version " + notes.ReleaseVersion;
mail.From = new MailAddress(sender);
mail.Body = GetEmailBody(notes);
mail.IsBodyHtml = true;
foreach (string r in recipients)
{
mail.To.Add(r);
}
foreach (string a in attachments)
{
mail.Attachments.Add(new Attachment(a));
}
client.Host = "pod51213.outlook.com";
client.Credentials = new NetworkCredential(username, password);
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(mail);
}
I am supposed to see the email appear in my inbox while the screen switches over to a screen saying email was sent. Its not giving me an actual error code. It just says operation timed out.
I was able to get the host I needed and get the function to run. The company I wrote the code for had their own host server. All I did to fix the code was delete the line that included client.Credentials, because I did not need that, and in the quotes for client.Host I replaced "pod51213.outlook.com" with "smtp.irco.com", which is the mail server for the company I built the program for.
I Think you should specify the port number
e.g.
SmtpClient("smtp.gmail.com", 587) // This for gmail
I have a web application using ASP.net and C#,in one step it will need
from the user to
send an email to someone with an attachments.
my problem is when the user will send the email i don't want to put their
password every time the user send.
i want to send an email without the password of the sender.
any way to do that using SMTP ?
and this is a sample of my code "not all".
the code is worked correctly when i put my password , but without it ,it
is not work, i need a way to send emails without put the password but
in the same time using smtp protocol.
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
// mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
}
I believe this can be accomplished easily, but with some restrictions.
Have a look at the MSDN article on configuring SMTP in your config file.
If your SMTP server allows it, your email object's from address may not need to be the same as the credentials used to connect to the SMTP server.
So, set the from address of your email object as you already are:
mail.From = new MailAddress(emailFrom);
But, configure your smtp connection one of two ways:
Set your app to run under an account that has permission to access the SMTP server
Include credentials for the SMTP server in your config, like this.
Then, just do something like this:
using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}
Let the configuration file handle setting up SMTP for you. This is also great because you don't need to change any of your code if you switch servers.
Just remember to be careful with any sensitive settings in your config file! (AKA, don't check them into a public github repo)
We use the excellent AuthSMTP service for outgoing mail from our MVC application. Until we upgraded to .Net 4.5.1 we used SmtpMail.SendAsync to send out multiple emails at once via IIS7. IIS7 is set to relay mail through AuthSMTP.
These days asynchronous code in .Net seems to work differently. We rolled back to SmtpMail.Send which has slowed the site down where multiple mails are sent. We are considering the following options.
Rewrite the code to work with the Task-based Asynchronous Pattern. We're fairly confused by this but could persevere if it's a good option.
Save email to the database and send it using a console application triggered as a scheduled task. We like this option because it gives us an archive of sent email. On the other hand we'd need to hit the database to store the emails, which may be slower than asking IIS to dump outgoing mail to a queue folder.
Have IIS save outgoing mail to a queue folder, and write a console application to process that queue. We could archive each message on disk, which is a worse archiving solution than storing in database.
Something else.
Can anyone tell us the most performant solution base on their experience?
Thanks!
Call your email function in a separate thread, that will send emails in background
Try this code.
public static void SendEmail(string from, string[] to, string[] CC, string[] BCC, string subject, string body, SMTPSettings _smtp = null)
{
Thread email = new Thread(delegate()
{
SendAsyncEmail(from, to, CC, BCC, subject, body, _smtp);
});
email.IsBackground = true;
email.Start();
}
private static void SendAsyncEmail(string from, string[] to, string[] CC, string[] BCC, string subject, string body, SMTPSettings _smtp = null)
{
try
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
if (_smtp != null)
{
client.Host = _smtp.SMTPServer;
client.Port = Convert.ToInt32(_smtp.SMTPPort);
client.EnableSsl = _smtp.SMTPEnableSSL;
client.Credentials = new System.Net.NetworkCredential(_smtp.SMTPUserEmail, SMTPPassword);
}
message.From = new MailAddress(from);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
foreach (string t in to)
{
message.To.Add(new MailAddress(t));
}
if (CC != null)
foreach (string c in CC)
{
message.CC.Add(new MailAddress(c));
}
if (BCC != null)
foreach (string b in BCC)
{
message.Bcc.Add(new MailAddress(b));
}
client.Send(message);
}
catch (Exception ex)
{
ErrorLogRepository.LogErrorToDatabase(ex, null, null, "");
}
}
I have a code for sending email through code, its as follows:
string subject = "SecureEmail: URS Scheduler - ";
string body = #"Message: My Message";
try
{
SmtpClient sm = new SmtpClient();
MailMessage msg = new MailMessage();
//msg.SubjectEncoding.
sm.Host = "email.myhost.com";
//Add Sender
msg.From = new MailAddress("abc#myhost.com");
//Add reciepents
sendMailToUsers(msg, "pqr#myhost.com");
//send message
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.Body = body;
sm.Send(msg);
I am able to send message but its not encrypted, its a plain Text.
When I go to my Outlook mail client and Send Mail with above recipients and body, and subject starting with "SecureEmail:", I get an Encrypted Email with a button "Open Message". When I click on Open Message it redirects me to https://web1.zixmail.net/s/e?b=domain&m=encrypted msg and other info,then I login into it and and able to see the plain text of mail body.
Please help me in getting above behaviour through my code.
Your company is using ZixMail, and your Outlook has a plugin to enable this. If you want to send ZixMail from C#, you'll need to use their toolset and API. Reffer to ZixMail documentation and support.
I have a small console application. It checks a few settings, makes some decisions, and sends an email. The problem is the email doesn't actually get sent until my application finishes. I want the email sent as soon as my method that sends the email completes.
Initially, I just created a MailMessage and called .Send(). That's when I noticed the mail was not being sent until the app finished.
Then I tried using the task parallel library.
var taskA = Task.Factory.StartNew(() => msg.Send());
Again, the messages don't get sent until my entire application finishes.
How do I sent an email when msg.send executes, not when the app completes?
SmptClient supports async sending of mail via SendAsync, however in practice in a web application this hangs the request thread.
To avoid blocking I recommend using the ThreadPool to fire off the email in a background thread. This won't block your application.
ThreadPool.QueueUserWorkItem(o => {
using (SmtpClient client = new SmtpClient(...))
{
using (MailMessage mailMessage = new MailMessage(...))
{
client.Send(mailMessage, Tuple.Create(client, mailMessage));
}
}
});
The most sure fire way to avoid delays would probably be to use a pickup directory, which will queue the message rather than send it immediately.
you should use a SMTP client. do it like this:
MailMessage mm = new MailMessage();
//fill in your message
NetworkCredential nc = new NetworkCredential(FromAddress, FromPassword);
SmtpClient sc = new SmtpClient(SmtpHost, SmtpPort);
sc.EnableSsl = true;
sc.Credentials = nc;
sc.Send(mm);
at this stage your mail will be sent.
But, sending an email is an async act, so it will take some time until you recive the mail.
Create a new MailMessage and send it with SmtpClient. It will send immediately. I will add an example.
EDIT: Populate the variables host, port with the smtp ser ver name and port number.
using (var mailer = new SmtpClient(host, port))
{
using (var message = new MailMessage(sender, recipient, subject, body) { IsBodyHtml = false })
{
mailer.UseDefaultCredentials = false;
mailer.Credentials = new NetworkCredential(user, pass);
mailer.EnableSsl = useSSL;
mailer.Timeout = Timeout;
mailer.Send(message);
}
}
If you still experience a delay, then the delay will be at the mail server.
Simply dispose the MailMessage and SmtpClient objects after the .Send() function.
SmtpClient smtpClient = new SmtpClient("server", 25);
smtpClient.UseDefaultCredentials = true;
MailMessage message = new MailMessage("ToAddress","FromAddress");
message.Subject = "Test email";
message.Body = "Test email";
smtpClient.Send(message);
message.Dispose();
smtpClient.Dispose();
Use SmtpClient with setting:
smtpClient.ServicePoint.MaxIdleTime = 2;
https://weblogs.asp.net/stanleygu/tip-14-solve-smtpclient-issues-of-delayed-email-and-high-cpu-usage