how to write a simple code that sends email - c#

i developed a simple website that stores in the user name and sends that to my emailid and then downloads a file.File is getting downloaded but not mailing me the username.
try
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("mygmailid");
mailMessage.From =new MailAddress("mydomainbasedemailid");
mailMessage.Subject = "ASP.NET e-mail test";
mailMessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!";
SmtpClient smtpClient=new SmtpClient("mail.mydomain.com",587);
smtpClient.Send(mailMessage);
Response.Write("E-mail sent!");
}
catch (Exception ex)
{
Response.Write("Could not send the e-mail - error: " + ex.Message);
}

Try to set the Smtp.Credentials like this:
string HOSTLOGIN = "YourHostLogin";
string HOSTPW = "YourTopSecretPasswort";
var credentials =
new System.Net.NetworkCredential() { UserName = HOSTLOGIN, Password = HOSTPW };
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
client.EnableSsl = true;

Related

asp c# send email without configuring sender credentials

I am trying to test sending out emails to users from a generic email such as noreply#company.com.
I want to do this in a button click event. How do I achieve this without using credentials?
I have tried several things but I always get errors.
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
mm.To.Add(new System.Net.Mail.MailAddress("Email Address", "Name"));
mm.From = new System.Net.Mail.MailAddress("Email Address");
mm.Sender = new System.Net.Mail.MailAddress("Email Address", "Name");
mm.Subject = "This is Test Email";
mm.Body = "<h3>This is Testing SMTP Mail Send By Me</h3>";
mm.IsBodyHtml = true;
mm.Priority = System.Net.Mail.MailPriority.High; // Set Priority to sending mail
System.Net.Mail.SmtpClient smtCliend = new System.Net.Mail.SmtpClient();
smtCliend.Host = "Your smtp server";
smtCliend.Port = 25; // SMTP port no
smtCliend.Credentials = new NetworkCredential("User Name", "Password");
smtCliend.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
try
{
smtCliend.Send(mm);
}
catch (System.Net.Mail.SmtpException ex)
{
lblMsg.Text = ex.ToString();
}
catch (Exception exe)
{
lblMsg.Text = "\n\n\n" + exe.ToString();
}
Thanks

Is email message sent from programmatically from C# will be found in gmail.com account?

I am using gmail to send email from C# program, my question is that email found under sent items if logged in into gmail.com via browser?
if I am sent an email from c# program and that email fails(bounce back) then Is failover notification found if I am logged in into gmail.com via browser?
if yes , then is there any additional settings to receive that? I want to show that in gmail.com via browser when I am login.
I don't really understand what you are asking but if you just need the code to send emails through gmail it is pretty simple
void SendMail_Click(object sender, EventArgs e)
{
var email = new Dto.IEmail();
if (EmailBody.Text == string.Empty && EmailSubject.Text == string.Empty)
{
XtraMessageBox.Show("please fill email body and subject");
return;
}
email.Body = EmailBody.Text;
email.Subject = EmailSubject.Text;
email.EmailAddress = "email#gmail.com";
email.ToAddress = "email#gmail.com";
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(email.EmailAddress);
message.To.Add(new MailAddress(email.ToAddress));
message.Subject = email.Subject;
message.Body = email.Body + "\n From user " + GlobalClass.UserLogin.USERNAME + "\n with body: " + _reportedfile;
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(email.EmailAddress, "gmailpassword");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch (Exception ex)
{
XtraMessageBox.Show("err: " + ex.Message);
}
}

Time out error while sending mail to gmail account using smtp port 465 in asp.net

public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.

Sending an email programmatically through an SMTP server

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("no-reply#company.us");
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);
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
}
var client = new SmtpClient("smtp.gmail.com", 587);
Credentials = new NetworkCredential("sendermailadress", "senderpassword"),
EnableSsl = true
client.Send("sender mail adress","receiver mail adress", "subject", "body");
MessageBox.Show("mail sent");
This is Adil's answer formatted for C#:
public static class Email
{
private static string _senderEmailAddress = "sendermailadress";
private static string _senderPassword = "senderpassword";
public static void SendEmail(string receiverEmailAddress, string subject, string body)
{
try
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(_senderEmailAddress, _senderPassword),
EnableSsl = true
};
client.Send(_senderEmailAddress, receiverEmailAddress, subject, body);
}
catch (Exception e)
{
Console.WriteLine("Exception sending email." + Environment.NewLine + e);
}
}
}
You didn't specify the port.
smtp.Port = 1111; // whatever port your SMTP server uses
The SMTP has three different "standard" ports: 25, 465 and 587. According to msdn documentation, the default value for the Port property is 25.

How to pass parameters into an HTML email template from C# Windows application to Send an email

Hi I need to send an email using template in c# windows application . I had created a template but i am unable to pass the parameters through the html template. Here is the template which i am using.
For this HTML Template i am calling this in my windows application and sending through gmail smtp. I am able to send the mail but unable to pass the parameters into it. Please Help me out.Here is the code where i am calling in my windows application
try
{
using (StreamReader reader = File.OpenText("H:\\Visitor Management_Project\\Visitor Management_Project\\Visitor Management_Project\\EmailTemplate.htm"))
{
SmtpClient SmtpServer = new SmtpClient("173.194.67.108", 587);
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Credentials = new System.Net.NetworkCredential("ambarishkesavarapu#gmail.com", "*******");
//SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
message = new MailMessage();
message.Subject = "Visitor Arrived";
//message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = "EmailTemplate.htm";
//message.BodyEncoding = System.Text.Encoding.UTF8;
message.From = new MailAddress("ambarishkesavarapu#gmail.com");
message.To.Add(lblCPEmail.Text);
message.Priority = MailPriority.High;
message.Body = reader.ReadToEnd();
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpServer.Send(message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How to add Parameters into HTML Template where i am getting all the parameters of that in the same page in Textboxes. Please help me out
I think you already discovered the answer yourself, but I will keep posting the answer instead.
In case you are using Windows Forms and not Windows Presentation Forms (The different only the design part and many new features that does not have on Windows Forms), what I have done is like this (to send email):
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
May this answer would help you.
Cheers!

Categories