Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Mail with an attachment using SMTP

Tags:

c#

asp.net

smtp

protected void Button1_Click(object sender, EventArgs e)
{
    var fromAddress = new MailAddress(fromid.Text, fromname.Text);
    var toAddress = new MailAddress(toid.Text, toname.Text);
    string fromPassword = pswd.Text;
    string subject = subjectbox.Text;
     string body = bodybox.Text;
     Attachment at = new Attachment(Server.MapPath("~/Penguins.jpg"));

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
        Timeout = 20000,

    };
    using (var message = new MailMessage(fromAddress, toAddress)
    {
        Subject = subject,
        Body = body,
        IsBodyHtml = false,


    })
    {
        message.Attachments.Add(at);
        smtp.Send(message);
    }

}

There is no error but while sending mail it takes some time and shows "Connection TimeOut" and not sending mail...:( Can any one tell where is the problem.

like image 581
Syed Yunus Avatar asked Oct 24 '25 18:10

Syed Yunus


1 Answers

try this code for your smtp mail with attachment problem

post.From = new MailAddress(From);
post.To.Add(To);
post.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
post.Subject = Subject;
post.Body = Body;

var htmlView = AlternateView.CreateAlternateViewFromString(post.Body, null, "text/html");
post.AlternateViews.Add(htmlView);

if (attachments != null && attachments.Count > 0)
{
    foreach (var at in attachments)
    {
        post.Attachments.Add(at1);
    }
}

post.IsBodyHtml = true;

//if you have relay privilege you can use only host data; 
//var host = "Your SMTP Server IP Adress";
//var postman = new SmtpClient(host);

//you dont have relay privilege you must be use Network Credential
var postman = new SmtpClient("Host Server Name", Port);
NetworkCredential cred = new NetworkCredential(mail adress, password);
postman.UseDefaultCredentials = false;
postman.Credentials = cred;
postman.Send(post);
post.Dispose();
return true;
like image 180
carlito Avatar answered Oct 26 '25 07:10

carlito



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!