How to Send Email With Attachment In Asp.Net

I need to attach an image with my email in asp.net the file is already added in the solution explorer but I dont know how to add this with my email please guide me

My current code is given below

public void SendMail()
{
    try
    {
        string receiverEmailId = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deb0bfb3bb9ebba6b3aef0bdb1b3">[email protected]</a>";
        string senderName = ConfigurationManager.AppSettings["From"].ToString();
        string mailServer = ConfigurationManager.AppSettings["SMTPServer"].ToString(); ;
        string senderEmailId = ConfigurationManager.AppSettings["SMTPUserName"].ToString();
        string password = ConfigurationManager.AppSettings["SMTPPasssword"].ToString();
        var fromAddress = new MailAddress(senderEmailId, senderName);
        var toAddress = new MailAddress(receiverEmailId, "Alen");
        string subject = "subject";
        string body = "body.";
        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential(fromAddress.Address, password)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }
    }
    catch (Exception ex)
    {
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Did you check out MailMessage.Attachments property (see MSDN)?

// create attachment and set media Type
//      see http://msdn.microsoft.com/de-de/library/system.net.mime.mediatypenames.application.aspx
Attachment data = new Attachment(
                         "PATH_TO_YOUR_FILE", 
                         MediaTypeNames.Application.Octet);
// your path may look like Server.MapPath("~/file.ABC")
message.Attachments.Add(data);

Method 2

create object of Attachment class with file name and add it into message’s Attachments property

  Attachment attachment = new Attachment("file.ext");
  message.Attachments.Add(attachment);

Method 3

public static bool SendMail(string strFrom, string strTo, string strSubject, string strMsg)
    {            
        try
        {                
            // Create the mail message
            MailMessage objMailMsg = new MailMessage(strFrom, strTo);

            objMailMsg.BodyEncoding = Encoding.UTF8;
            objMailMsg.Subject = strSubject;
            objMailMsg.Body = strMsg;
            Attachment at = new Attachment(Server.MapPath("~/Uploaded/txt.doc"));
            objMailMsg.Attachments.Add(at);
            objMailMsg.Priority = MailPriority.High;
            objMailMsg.IsBodyHtml = true;

            //prepare to send mail via SMTP transport
            SmtpClient objSMTPClient = new SmtpClient();
            objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
            objSMTPClient.Send(objMailMsg);
            return true;                
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Reference

Method 4

Sending email with attachment in ASP.Net with a simple coding. In this article I will show you, how you can do this.

Index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="_Default" Debug="true" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<title>Careers</title>
</head>

<body>
<form id="form2" runat="server">

<div class="form-group">
<label for="exampleInputName">Name</label>
<asp:TextBox ID="txtName" runat="server" class="form-control" placeholder="Name"></asp:TextBox>
</div>
<div class="form-group">
<label for="exampleInputEmail">Email address</label>

<asp:TextBox ID="txtEmail" runat="server" class="form-control" placeholder="Enter Email"></asp:TextBox>
</div>
<div class="form-group">
<label for="txtcontact">Contact no</label>
<asp:TextBox ID="txtcontact" runat="server" class="form-control" placeholder="Contact no"></asp:TextBox>
</div>
<div class="form-group">
<label for="txtjobTitle">Job Title</label>
<asp:DropDownList ID="txtjobTitle" runat="server" class="form-control">
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
<asp:ListItem Text="Social Media Experts" Value="1"></asp:ListItem>
<asp:ListItem Text="Business Developement Executives" Value="2"></asp:ListItem>
<asp:ListItem Text="Copywriters" Value="3"></asp:ListItem>
<asp:ListItem Text="Graphic Designers" Value="4"></asp:ListItem>
<asp:ListItem Text="Web Designers" Value="5"></asp:ListItem>
<asp:ListItem Text="Animation Designers" Value="6"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="form-group">
<label for="txtjobExp">Experience</label>
<asp:DropDownList ID="txtjobExp" runat="server" class="form-control">
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
<asp:ListItem Text="0-1" Value="1"></asp:ListItem>
<asp:ListItem Text="1-3" Value="2"></asp:ListItem>
<asp:ListItem Text="3-5" Value="3"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="form-group">
<label for="exampleInputFile">Upload Resume</label>
<asp:FileUpload ID="fileUploader" runat="server" />
</div>

<asp:Button ID="bttn_Send" Text="Submit" runat="server" OnClick="bttn_Send_Click" class="btn" />
</form>
</body>

</html>

Index.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void bttn_Send_Click(object sender, EventArgs e)
{
string from = “<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90f9fef6ffd0e3e5e2e9f1e2e0e2f1e6f5f5febde7ffe2f4e0e2f5e3e3bef3fffd">[email protected]</a>”;
string textTo = “<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="187b796a7d7d6a6b586b6d6a61796a686a796e7d7d76356f776a7c686a7d6b6b367b7775">[email protected]</a>”;
using (MailMessage mail = new MailMessage(from, textTo))
{

mail.Subject = “Careers – Surya R Praveen WordPress”;

mail.Body = string.Format(@”
Name: {0}
Email: {1}
Contact: {2}
Job: {3}
Experience: {4}
“, txtName.Text, txtEmail.Text, txtcontact.Text, txtjobTitle.SelectedItem.Text, txtjobExp.SelectedItem.Text);

if (fileUploader.HasFile)
{
string fileName = Path.GetFileName(fileUploader.PostedFile.FileName);
mail.Attachments.Add(new Attachment(fileUploader.PostedFile.InputStream, fileName));
}
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = “mail.suryarpraveen-wordpress.com”;
smtp.EnableSsl = false;
NetworkCredential networkCredential = new NetworkCredential(from, “<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7f6d6d69716c7a5e2e2e29">[email protected]</a>”);
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 25;
smtp.Send(mail);
ClientScript.RegisterStartupScript(GetType(), “alert”, “alert(‘Message has been sent successfully.’);”, true);
}
}
}

https://suryarpraveen.wordpress.com/2017/08/22/how-to-send-email-with-attachment-in-asp-net/

Method 5

protected void Send_Button_Click(object sender, EventArgs e)
{

    MailMessage mail = new MailMessage();

    mail.From = new MailAddress("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="baf5d4dffaddd7dbd3d694d9d5d7">[email protected]</a>");
    mail.To.Add(new MailAddress("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8fcdfc7e8d1c9c0c7c786cbc7c5">[email protected]</a>"));
    mail.Bcc.Add(new MailAddress("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22764a50474762454f434b4e0c414d4f">[email protected]</a>"));
    mail.Subject = "Testing E-mail By ASP.NET";
    mail.Body = "This is only for Demo ";

    if (FileUpload1.HasFile)
    {
        Attachment attach = new Attachment(FileUpload1.PostedFile.InputStream ,FileUpload1.PostedFile.FileName);

        mail.Attachments.Add(attach);
    }


    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

    System.Net.NetworkCredential credential = new System.Net.NetworkCredential();

    credential.UserName = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eea1808bae89838f8782c08d8183">[email protected]</a>";
    credential.Password = "123456789";

    smtp.Credentials = credential;
    smtp.EnableSsl = true;
    smtp.Send(mail);
}

Method 6

Here is a code…

public void MailSend(string strfrom, string strto, string strSubject, string strBody, string resumename, string sresumename)
{
    try
    {
        MailMessage msg = new MailMessage(strfrom, strto);// strEmail);
       
        msg.Bcc.Add("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0d8d8e0d8d8d8d88ec3cfcd">[email protected]</a>");
        msg.Body = strBody;
        msg.Subject = strSubject;
        msg.IsBodyHtml = true;
        if (resumename.Length > 0)
        {
            Attachment att = new Attachment(Server.MapPath(VirtualPathUtility.ToAbsolute("~/User_Resume/" + resumename)));
            msg.Attachments.Add(att);
        }
        if (sresumename.Length > 0)
        {
            Attachment att1 = new Attachment(Server.MapPath(VirtualPathUtility.ToAbsolute("~/User_Resume/" + sresumename)));
            msg.Attachments.Add(att1);
        }
        System.Net.Mail.SmtpClient cli = new System.Net.Mail.SmtpClient("111.111.111.111",25);
        cli.Credentials = new NetworkCredential("nnnnnnn", "yyyyyy");
        cli.Send(msg);
        msg.Dispose();
        ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('Inquiry submitted successfully');", true);
    }
    catch (Exception ex)
    {
        ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('"+ex.Message+"');", true);
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x