Anonymous Anonymous - 3 months ago 9
C# Question

c# Sending emails in threads using 1 connection

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:


  1. can I send each email and only upload my pdf resume once?

  2. 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.

Answer

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.

Comments