Asp.net 4.0 Sending Emails - asp.net

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);
}

Related

ASP.Net : Send email with Images embedded in Rich Text HTML body

Sending a mail along with embedded image & HTML Text using asp.net.
I have tried like this:
public ActionResult Contact(tblCredential data)
{
string emailAddress = data.UserName;
string password = data.Password;
if (!string.IsNullOrEmpty(emailAddress))
{
//Send email to consultancy
string htmlText = "<img src='R:/MVC#2/EmailWithHtmlBody/EmailWithHtmlBody/images/message.jpg'></img>
<h1>Thank you</h1>";
string from = "******#gmail.com"; // Your Mail-id here emailAddress
string #touser = emailAddress; // To Mail-id
MailMessage mail = new MailMessage(from, touser);
{
mail.Subject = emailAddress + " sent a message";
mail.Body = htmlText;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", EnableSsl = true };
NetworkCredential networkCredential = new NetworkCredential(from, "*****"); //Your Password here..
smtp.UseDefaultCredentials = false;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
}
}
return RedirectToAction("Index");
}
Email is sent but HTML code is not working. In the mail it is showing HTML tags.
Help me.
In your code you are setting mail.IsBodyHtml = true; first, then mail.IsBodyHtml = false; again. Obviously, this won't work.
Btw: You cannot embed an image using the local path. The recipient will not have your image on his local machine. Embed it using inline embedding (Base64 Encoding) like it is shown here: https://sendgrid.com/blog/embedding-images-emails-facts/
<img alt="My Image" src="data:image/jpeg;base64,/9j/4S/+RXhpZgAATU0AKgAAAAgACAESAAMAENkDZ5u8/61a+X...more encoding" />
Try this template.
It helps to use smtp.port=25
try
{
MailMessage msg = new MailMessage ();
MailAddress fromAdd = new MailAddress("fromemail#email.com");
msg.[To].Add("toemail#email.com");
msg.Subject = "Choose Session Members";
msg.From = fromAdd;
msg .IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg .BodyEncoding = Encoding.Default;
msg.Body = "<center><table><tr><td><h1>Your Message</h1><br/><br/></td></tr>";
msg.Body = msg.Body + "</table></center>";
SmtpClient smtpClient = new SmtpClient ("smtp.yourserver.com", "25");
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("yourname#yourserver.com", "password");
smtpClient .DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(msg);
smtpClient.Dispose();
}

Can't Send Emails From my Website

Here I am in a strange situation. When I send the email from localhost it is working fine but when I upload the page to the server and try to send email, I get the following error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I'm displaying the error message in a label for testing purpose and the try is also misplaced I know, I will set it later.
the code I am using is
if (Page.IsValid)
{
try
{
StringBuilder message = new StringBuilder();
message.Append("Hello My Name is ");
message.Append(txtName.Text);
message.AppendLine();
message.AppendLine("My Contact Number " + txtContactNumber.Text.ToString());
message.AppendLine();
message.AppendLine();
message.AppendLine("My Email Id Is " + txtFromEmailAddress.Text.ToString());
message.AppendLine();
message.Append(txtEmailBody.Text);
MailMessage mailMessage = new MailMessage("xxx#gmail.com", "yyy#gmail.com");
mailMessage.Subject = "New Client Query";
mailMessage.Body = message.ToString();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);
//smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "xxx#gmail.com",
Password = "password"
};
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
txtContactNumber.Text = "";
txtFromEmailAddress.Text = "";
txtName.Text = "";
txtEmailBody.Text = "";
lblEmailStatus.Text = "Email Sent Successfully.";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
catch(Exception ex)
{
lblEmailStatus.Text = ex.Message + " <br> " + ex.Source;
}
}
else
{
lblEmailStatus.Text = "Error! Email Not Sent ";
lblEmailStatus.ForeColor = System.Drawing.Color.Yellow;
}
I have googled for a couple of hours and checked links at this site as well but I still cant figure it out.
Now I request you guys here if any one have any solutions / hint.
Try this
public string SendEmailTest(String EmailMessage, String FromMail, String MailPassword, String MailServer, String To, String CC, String BCC, String DisplayName, String Subject, String Attachment)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress;
fromAddress = new MailAddress(FromMail);
smtpClient.Host = MailServer;
smtpClient.Port = 25;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(FromMail, MailPassword);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
message.From = fromAddress;
message.To.Add(new MailAddress(To, DisplayName));
if (CC != "")
message.CC.Add(new MailAddress(CC, DisplayName));
if (BCC != "")
message.Bcc.Add(new MailAddress(BCC, DisplayName));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = EmailMessage;
if (Attachment != "")
message.Attachments.Add(new Attachment(Attachment));
message.Priority = MailPriority.High;
smtpClient.Send(message);
return "SendEmail";
}
catch (Exception ex)
{
return "Email :" + ex;
}
}
i got the reason finally .
the email i was sending emails from was kind of hacked some days before and for the security reasons google team had kind of marked my email as unsecure . i changed the emails address and it is working fine thanks you all.
Based on the Google Gmail Documentation it would appear that the Port should be 587 not 25. I found a few other questions that seem to be related here and here.
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;

How can I attach a file to an email?

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);
}

Send email with System.Web.Mail

I want send email in asp.
I use this code
using System.Web.Mail;
MailMessage msg = new MailMessage();
msg.To = "aspnet#yahoo.com";
msg.From = "info#mysite.com";
msg.Subject = "Send mail sample";
msg.BodyFormat = MailFormat.Html;
string msgBody="Hello My Friend. This is a test.";
msg.Body = msgBody ;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(msg);
But i get error :
Bad sequence of commands. The server response was: This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.
How to send email with asp?
I use This code .
MailMessage msg = new MailMessage();
msg.Body = "Body";
string smtpServer = "mail.DomainName";
string userName = "info#mysite.com";
string password = "MyPassword";
int cdoBasic = 1;
int cdoSendUsingPort = 2;
if (userName.Length > 0)
{
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", smtpServer);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", cdoSendUsingPort);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", cdoBasic);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", userName);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password);
}
msg.To = user.Email;
msg.From = "info#Mysite.com";
msg.Subject = "Subject";
msg.BodyEncoding = System.Text.Encoding.UTF8;
SmtpMail.SmtpServer = smtpServer;
SmtpMail.Send(msg);
You might need to provide credentials.
example:
smtpMail.Credentials = new NetworkCredential("username", "password")
If you are trying to send email without authenticating, I am afraid that's impossible. If any users in your web site can send emails without password, that's horrible. It will allow user to send email from other person account. So considering security, sending email will required to provide email address and password
var fromAddress = ""; // Email Address here. This will be the sender.
string fromPassword = ""; // Password for above mentioned email address.
var toAddress = "";// Receiver email address here
string subject = "Hi";
string body = "Body Text here";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com"; // this is for gmail.
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
smtp.Send(fromAddress, toAddress, subject, body);
[Edited]
Sorry My mistake i didn't noticed that. They both used for same purpose. If you are using higher version (2.0 or later) of .Net framework, then use System.Net.Mail. If you use System.Web.Mail it only shows a warning saying this is deprecated. But that will work.
Here is the answer for System.web.mail
MailMessage mail = new MailMessage();
mail.To.Add("to#domain.com");
mail.From = new MailAddress("from#domain.com");
mail.Subject = "Email using Gmail";
mail.Body = "";
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(mail.From,"YourPassword");
smtp.Send(mail);

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