Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an email programmatically through an SMTP server

Tags:

c#

smtp

Trying to send an email through an SMTP server, but I'm getting a nondescript error on the smtp.Send(mail); snippet of code.

Server side, the relay IP addresses look correct. Scratching my head about what I'm missing.

MailMessage mail = new MailMessage();
mail.To.Add(txtEmail.Text);

mail.From = new MailAddress("[email protected]");
mail.Subject = "Thank you for your submission...";
mail.Body = "This is where the body text goes";
mail.IsBodyHtml = false;

SmtpClient smtp = new SmtpClient();
smtp.Host = "mailex.company.us";
smtp.Credentials = new System.Net.NetworkCredential
     ("AdminName", "************");

smtp.EnableSsl = false;


if (fileuploadResume.HasFile)
{
    mail.Attachments.Add(new Attachment(fileuploadResume.PostedFile.InputStream,
        fileuploadResume.FileName));
}

smtp.Send(mail);
like image 616
Rex_C Avatar asked Mar 13 '26 18:03

Rex_C


1 Answers

Try adding smtp.DeliveryMethod = SmtpDeliveryMethod.Network; prior to send.

For reference, here is my standard mail function:

public void sendMail(MailMessage msg)
{
    string username = "username";  //email address or domain user for exchange authentication
    string password = "password";  //password
    SmtpClient mClient = new SmtpClient();
    mClient.Host = "mailex.company.us";
    mClient.Credentials = new NetworkCredential(username, password);
    mClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    mClient.Timeout = 100000;
    mClient.Send(msg);
}

Typically called something like this:

MailMessage msg = new MailMessage();
msg.From = new MailAddress("fromAddr");
msg.To.Add(anAddr);

if (File.Exists(fullExportPath))
{
    Attachment mailAttachment = new Attachment(fullExportPath); //attach
    msg.Attachments.Add(mailAttachment);
    msg.Subject = "Subj";
    msg.IsBodyHtml = true;
    msg.BodyEncoding = Encoding.ASCII;
    msg.Body = "Body";
    sendMail(msg);
}
else
{
    //handle missing attachments
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!