How can I attach a file to an email? - asp.net

I am working on a project that has to send an email with an attachment. I have achieved sending mail, but I don't know how to attach an excel file.
Could someone point me in the right direction? Here's my code so far:
private void sendmail(string Tomailid, string name)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("ehsimsemail#gmail.com");
mail.To.Add(Tomailid);
mail.Subject = "Test Mail";
StringBuilder sb = new StringBuilder();
sb.Append("Dear ");
sb.Append(string.Format("{0} ", name));
//sb.Append("Yuvaraj");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append("UCR No : ");
sb.Append("3256987");
sb.Append(" ");
sb.Append("HAS BEEN SENT FOR YOUR REVIEW AND APPROVAL");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append("For action, Please click Here");
sb.Append(Environment.NewLine);
sb.Append("This is a automatic generated report from Advanced Incident Management System (EHS-IMS). Please do not reply to this mail.");
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append("Thanks & Regards,");
sb.Append(Environment.NewLine);
sb.Append("EHSIMS TEAM");
mail.Body = sb.ToString();
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.Port = 587;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new System.Net.NetworkCredential("ehsimsemail#gmail.com", "ehsims123");
SmtpServer.Send(mail);
}

That is so easy. So much material available on Internet.
Have a look at this link :
http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments.aspx
Short Code :
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);

You have to attach the file to your message.
mail.Attachments.Add(New Attachment(pathToExcelFile))
where pathToExcelFile is the file path to the file you want to send.
Make sure you have access rights to the file.
see the following for more information:
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx

protected void btnSendMail_Click(object sender, EventArgs e)
{
string to = "reciever#gmail.com";
string from = "frommail#gmail.com";
string subject = "Mail Subject";
string body = "Mail Message";
MailMessage msgObj = new MailMessage();
msgObj.To.Add(to);
msgObj.Subject = subject;
msgObj.Body = body;
msgObj.IsBodyHtml = true;
msgObj.Attachments.Add(new Attachment(#"D:\sample.xlx"));
MailAddress objMail = new MailAddress(from, "emailCampaign", System.Text.Encoding.UTF8);
msgObj.From = objMail;
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.Credentials = new System.Net.NetworkCredential(from, "password");
smtp.EnableSsl = true;
smtp.Send(msgObj);
}

Related

How to get Dynamic Data in email newsletter from the website in asp.net c#?

I have a newsletter design in which i have to bind data dynamically and send mail to users in asp.net c# through noreply#xyz.com
I tried but getting error of authentication if anyone knows please sort out the problem.
MailMessage Msg = new MailMessage();
MailAddress fromMail = new MailAddress("abc#gmail.com");
// Sender e-mail address.
Msg.From = fromMail;
// Recipient e-mail address.
Msg.To.Add(new MailAddress("xyz#gmail.com"));
// Subject of e-mail
Msg.Subject = "Send Gridivew in EMail";
Msg.Body += "Please check below data <br/><br/>";
Msg.Body += GetGridviewData(gvUserInfo);
Msg.IsBodyHtml = true;
string sSmtpServer = "";
sSmtpServer = "smtp.gmail.com";
SmtpClient a = new SmtpClient();
a.Host = sSmtpServer;
a.EnableSsl = true;
a.Port = 587;
a.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
a.Credentials = new NetworkCredential("abc#gmail.com", "abc#123");
a.Send(Msg);
Grid View Code
public string GetGridviewData(GridView gv)
{
StringBuilder strBuilder = new StringBuilder();
StringWriter strWriter = new StringWriter(strBuilder);
HtmlTextWriter htw = new HtmlTextWriter(strWriter);
gv.RenderControl(htw);
return strBuilder.ToString();
}

Send email using gmail: The operation has timed out

I´m trying to configure my console application to send an email to the gmail relay server.
the code i´m using is the next :
class Program
{
static void Main(string[] args) {
string header;
string body;
string emailTo;
string emailFrom = "anton.selin#inbox.com";
Console.WriteLine("Enter the header : ");
header = Console.ReadLine();
Console.WriteLine("Enter the message body : ");
body = Console.ReadLine();
Console.WriteLine("Enter your email : ");
emailTo = Console.ReadLine();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 465);
smtpClient.Credentials = new System.Net.NetworkCredential("anton.selin1#gmail.com", "**********");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom,"anton selin");
mail.To.Add(new MailAddress(emailTo));
mail.Body = body;
mail.Subject = header;
Console.WriteLine("Sending email...");
smtpClient.Send(mail);
Console.WriteLine("Email sent...");
Console.ReadKey();
}
}
when i run the code it gives me a timeout error :
{"The operation has timed out."}
how can i configure my application to be able to send email from console app or web app(from localhost)?
Check for this, I think this is your issue
string emailFrom = "anton.selin#inbox.com";
smtpClient.Credentials = new System.Net.NetworkCredential("anton.selin1#gmail.com", "**********");
mail.From = new MailAddress(emailFrom,"anton selin");
you are using gmail to send your mail whereas you should be using anton.selin#inbox.com credentials to send mail and not Gmail's
Try this code to mail :
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(Username);
mail.To.Add(emailTo);
mail.Subject = Subject;
mail.Body = Body;
SmtpServer.Port = 587; // Also Add the port number to send it, its default for Gmail
SmtpServer.Credentials = new System.Net.NetworkCredential(Username, Password);
SmtpServer.EnableSsl = true;
SmtpServer.Timeout = 20000; // Add Timeout property
SmtpServer.Send(mail);
let me know if it works.

Mail excel attachment in asp.net C#

I am trying to attach a excel file with mail, but not getting where I am doing the mistake. There is no error coming but mail does not get send. When I try to check the server path of file with file exist. it show me true, so my file path is correct.
Mail is going properly without attachment.
MailMessage Msg = new MailMessage();
Msg.Subject = "User Creation";
string body = MailSending.PrepareMailBodyWith("WelcomeTemplate.htm", "LoginID", LoginID, "password", password);
string clientCoverage = System.Web.HttpContext.Current.Server.MapPath("~/file/abc.xlsx");
bool isFile = false;
if (File.Exists(clientCoverage))
{
isFile = true;
}
byte[] bytes = System.IO.File.ReadAllBytes(clientCoverage);
MemoryStream stream = new MemoryStream(bytes);
lblerror.Text = avnTutorial + isFile.ToString() ;
Attachment attachment = new Attachment(stream, "document.xlsx");
Msg.Attachments.Add(attachment);
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.From = new MailAddress("info#xyz.in");
Msg.To.Add(new MailAddress(Email));
SmtpClient client = new SmtpClient();
client.Host = "mail.xyz.in";
client.Port = 25;
client.Credentials = new System.Net.NetworkCredential("info#xyz.in", "xyz");
client.Send(Msg);
I tried with without memory stream also here is the code but does not work.
Attachment attachment = new Attachment(clientCoverage, MediaTypeNames.Application.Octet);

Asp.net 4.0 Sending Emails

I have aspx page where i have the email field like this
<input class="span12" type="text" placeholder="EMAIL" id="Email" name="Email" runat="server" />
In my Csharp file i have code and using Request["Email"] to get the address when visitor enter the email address which can be any so i want to email them as well my code is like Below, But it does not work, I am using .net 4.0, where i can change then that dynamic email whatever it would be i could get it and send email.
private void SendEmail(int RefNum)
{
var customerEmail = Request["Email"]; //getting value from aspx page.
MailMessage ObjEmail = new MailMessage();
ObjEmail.SendFrom = "carlaza#hotmail.ca";
ObjEmail.SendTo = "zjaffary#hotmail.com";
ObjEmail.SendCC = "jaffary_zafar#hotmail.com";
ObjEmail.SendBCC = customerEmail ;
ObjEmail.Subject = "test Subject ";
//Development
//SmtpMail.SmtpServer = "tormail.corp.kkt.ca";
//Production At Bell
SmtpMail.SmtpServer = "tormail.corp.kkt.ca";
ObjEmail.BodyFormat = MailFormat.Html;
string strBody1 = "Test message " ;
ObjEmail.Priority = MailPriority.High;
try {
SmtpMail.Send(ObjEmail);
lblResponse.Text = "Thank you for sending the form !";
Response.AddHeader("Refresh", "2;URL=index.aspx");
}
catch (Exception exc){
Response.Write("Send failure: " + exc.ToString());
}
}
You should use authetication information from web mail server. (user name and password) If not, that is not actual e-mail.
You can see the code and can work
SmtpClient SmtpServer = new SmtpClient("smtp.live.com");
var mail = new MailMessage();
mail.From = new MailAddress("youremail#hotmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Test Mail - 1";
mail.IsBodyHtml = true;
string htmlBody;
htmlBody = "Write some HTML code here";
mail.Body = htmlBody;
SmtpServer.Port = 587;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("youremail#hotmail.com", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Please see the topic. I think it is helpfull for you.
How to add smtp hotmail account to send mail
How to add smtp hotmail account to send mail
try this
protected void sendEmail(string subject, string ToEmail, string msg)
{
String body = msg;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("your_email_id");
smtpClient.Host = "smtp.gmail.com";//host
smtpClient.Port = 587;//port no. default 25
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("your_email_id", "password");
message.From = fromAddress;
message.To.Add(ToEmail);//if more than comma seprated
message.Subject = subject;
message.Priority = MailPriority.High;
message.Body = body;
message.IsBodyHtml = true;
smtpClient.Send(message);
}

how to attach a file in email using shared hosting server?

I want to attach a file dynamically and send it through mail. So can someone please let me know how can i send it with attachment.
You can use this code.
using System.Net.Mail;
private void SendEmail()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("YourEmailAddress#domain.com");
message.To.Add(new MailAddress("Recipient#domain.com"));
message.Subject = "Subject";
message.Body = "Email Message Body";
// Add attachment
string attachmentPath = Server.MapPath("~/AttachmentPath.jpg");
message.Attachments.Add(new Attachment(attachmentPath));
// Connect to GoDaddy SMTP
SmtpClient smtp = new SmtpClient("relay-hosting.secureserver.net");
smtp.Credentials = new System.Net.NetworkCredential("Username","Password");
smtp.Port = 25;
smtp.EnableSsl = false;
// Send the message
smtp.Send(message);
}
you can try with this code
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("...");/:Adjust your adress
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
SmtpServer.Port = ..; //Replace with your port number
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);

Resources