Sending mail via C# - c#

I am trying to send an email to myself via C# using gmail stmp server but I was getting an email from the gmail team saying "Google just blocked a less secure app from accessing your Google Account." . Now I have changed the settings to allow less secure apps to sign in google but I am not able send an email to myself.Below is my code.
private static string sendMail(System.Net.Mail.MailMessage mm)
{
try
{
string smtpHost = "smtp.gmail.com";
string userName = "myemail#gmail.com";//write your email address
string password = "xxxxxx";//write password
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return "Send Sucessfully";
}
private void f()
{
i = i + 1;
string sysName = string.Empty;
string sysUser = string.Empty;
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("myemail#gmail.com");
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("myemail#gmail.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
sysName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
sysUser = System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString();
mm.Subject = sysName + " " + sysUser;
string filename = string.Empty;
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
MessageBox.Show(sendMail(mm).ToString());
//sendMail(mm);
}
private void Form1_Load(object sender, EventArgs e)
{
f();
}
Also I tried the same with my yahoo account.Then also I didnt receive any email at all.
I had changed port to 465 and smtphost to "mail.yahoo.com" and email address to mymail#yahoo.com

protected void SendMail()
{
// Gmail Address from where you send the mail
var fromAddress = "Gmail#gmail.com";
// any address where the email will be sending
var toAddress = YourEmail.Text.ToString();
//Password of your gmail address
const string fromPassword = "Password";
// Passing the values and make a email formate to display
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
you have use this code .
it is running code.

Go to google account settings, and allow less secure applications.
https://myaccount.google.com/u/1/security?utm_source=OGB#signin
At the bottom "Allow less secure apps" slider is the one you need to use.
Default google SMTP settings are here.

Related

Page does not open when clicked on URL

private string sendEmail(string emailId,string userID)
{
try
{
userID = Encrypt(userID);
MailMessage mail = new MailMessage();
mail.To.Add(emailId);
mail.From = new MailAddress("");
//mail.Subject = "Your password for account " + emailId;
string userMessage = "http://localhost/LoginWithSession/ResetPassword" + userID;
userMessage = userMessage + "<br/><b>User Id:</b> " + emailId;
//userMessage = userMessage + "<br/><b>Passsword: </b>" + password;
string Body = "<br/><br/>Please click on link to reset your password:<br/></br> " + userMessage + "<br/><br/>Thanks";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("harianasaif#gmail.com", "test");
// Smtp Email ID and Password For authentication
smtp.EnableSsl = true;
smtp.Send(mail);
return userMessage;
}
catch (Exception ex)
{
return "Error............" + ex;
}
}
**1. This is my code to send email
Problem is I cannot open Reset Page when clicked on URL
I have created the virtual directory as well**
Please check this
Here you need to add <a> tag for called the URL.
//Create one function for getting URL run time like localhost or any domain name
public string GetUrl()
{
var request = Request;
return string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, (new System.Web.Mvc.UrlHelper(request.RequestContext)).Content("~"));
}
private string sendEmail(string emailId,string userID)
{
try
{
userID = Encrypt(userID);
MailMessage mail = new MailMessage();
mail.To.Add(emailId);
mail.From = new MailAddress("");
//mail.Subject = "Your password for account " + emailId;
string userMessage = string.Concat("<a href='",GetUrl(), "LoginWithSession/ResetPassword/", userID,"'>");
userMessage = userMessage + "<br/><b>User Id:</b> " + emailId+"</a>";
//userMessage = userMessage + "<br/><b>Passsword: </b>" + password;
string Body = "<br/><br/>Please click on link to reset your password:<br/></br> " + userMessage + "<br/><br/>Thanks";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //SMTP Server Address of gmail
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential();
// Smtp Email ID and Password For authentication
smtp.EnableSsl = true;
smtp.Send(mail);
return userMessage;
}
catch (Exception ex)
{
return "Error............" + ex;
}
}

C# receive error sending a email

ERROR: Service not available, closing transmission channel. The server response was: Resources temporarily unavailable - Please try again later
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "mail#yahoo.com";
string password = "mailpass";
string emailTo = "sendemail#yahoo.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
//mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
//mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
What should I do?
You need to make sure an external application has permission to send emails through your email before you can proceed.

the operation has timed out system net mail smtpexception

I want to send mail using mail web application. While sending mail showing time out error. Help me to find a proper solution.
protected void btnsubmit_Click(object sender, EventArgs e)
{
Ticket_MailTableAdapters.tbl_TicketTableAdapter tc;
tc = new Ticket_MailTableAdapters.tbl_TicketTableAdapter();
DataTable dt = new DataTable();
dt = tc.GetEmail(dpl_cate.SelectedValue);
foreach (DataRow row in dt.Rows)
{
string eml = (row["Emp_Email"].ToString());
var fromAddress = "myMail#gmail.com";
var toAddress = eml;
const string fromPassword = "*****";
string body = "Welcome..";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
smtp.Timeout = 600000;
}
}
Use This Working Code.
const string vMailFm = "myMail#gmail.com";
var vMailTo = ((txtEmailId.Text == "") ? "myMail#gmail.com" : txtEmailId.Text);
MailMessage vMail = new MailMessage(vMailFm, vMailTo);
const string vSubject = "Center Detail From SAFE";
var vDetails = "";
vDetails += "Dear User,<br><br>";
vDetails += "Kindly find the user details of your registration with SAFE<br><br>";
vDetails += "Your UserName Is - " + vMailTo + "<br>";
vDetails += "Your Password Is - " + Convert.ToString(ViewState["password"]) + "<br>";
vDetails += "<br>";
vDetails += "Registration has been Successfully Completed....";
vDetails += "<br><br>";
vMail.Subject = vSubject;
vMail.Body = vDetails;
vMail.IsBodyHtml = true;
SmtpClient vSmpt = new SmtpClient();
System.Net.NetworkCredential smtpUser = new System.Net.NetworkCredential("myMail#gmail.com", "Password123");
vSmpt.Host = "smtp.gmail.com";
vSmpt.Port = 587;//for local
// vSmpt.Port = 25;//for online
vSmpt.EnableSsl = false;
vSmpt.DeliveryMethod = SmtpDeliveryMethod.Network;
vSmpt.UseDefaultCredentials = false;
vSmpt.Credentials = smtpUser;
vSmpt.Send(vMail);

Send email in ASP.NET C#

I'm creating a contact page for visitors of my web site to send me email (in C#). When trying, I got an error about EHLO argument(s). Here is my code:
I got the error:
The server response was: Syntactically invalid EHLO argument(s).
Please, help
try
{
MailMessage _email = new MailMessage();
String MessageString = "";
MessageString = "<br>";
MessageString += "<b>Message from " + champNom.Value + "</b><br /><br />";
MessageString += "<br/><br/>";
MessageString += champMail.Text;
_email.Subject = "Mail from " + champNom.Value + " (Email adress: " + champEmail.Text + ")";
_email.From = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["SenderForEmail"].ToString(), "MyName");
_email.To.Add(new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["AdminForEmail"].ToString(), "MyName"));
if (chkCCMyself.Checked) {
_email.CC.Add(new System.Net.Mail.MailAddress(champEmail.Text, champNom.Value));
}
_email.Body = MessageString;
_email.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.EnableSsl = false;
//smtp.UseDefaultCredentials = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Host = System.Configuration.ConfigurationManager.AppSettings["HostForEmail"].ToString();
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["SenderForEmail"].ToString(), System.Configuration.ConfigurationManager.AppSettings["SenderPswdForEmail"].ToString());
smtp.Send(_email);
Page.RegisterStartupScript("UserMsg", "<script>alert('Mail envoyé avec succès...');if(alert){ window.location='contact.aspx';}</script>");
}catch(Exception err){
champMail.Text += Environment.NewLine + err.Message;
}
Thanks in advance
As documented here http://forums.asp.net/t/1622198.aspx?Syntactically+invalid+EHLO+argument+s+emailing
If you email having problem with rejected EHLO or HELO, caused by syntactically invalid argument(s).
1.Possible the hostname contains underscore(_).
2.This is not standard practice, having _ for your domain
3.for example takizo_mail.takizo.com
4.Most of the mail server rejected hostname with underscore.
5.Possibility is a Windows Admin
Make sure the server-name has only latin-characters in it, and no special symbols like underscore etc.
MailMessage msg = new MailMessage("from#a.com", "To#y.com");
msg.Subject = "Intraday";
msg.Sender = new MailAddress("sender#y.com");
msg.IsBodyHtml = false; //to preserve line breaks and to avoid the need for <br>s
msg.Body = "Body";
SmtpClient client = new SmtpClient("Server");
client.Send(msg);

trying to send a basic email to folder

I am trying to send a basic email to a folderbut howerver, even though I do receive the email, the body is missing completely.
private void MailReport()
{
string to = "arianul#gmail.com";
string From = "ArianG#lr.co.za";
string subject = "Report";
**string Body = "Dear sir ,<br> Plz Check d Attachment <br><br>";**
bool send = sendMail(to, From, subject, Body);
if (send == true)
{
string CloseWindow = "alert('Mail Sent Successfully!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
else
{
string CloseWindow = "alert('Problem in Sending mail...try later!');";
ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
}
}
public bool sendMail(string to, string from, string subject, string body)
{
bool k = false;
try
{
MailMessage msg = new MailMessage(from, to);
msg.Subject = subject;
AlternateView view;
SmtpClient client;
StringBuilder msgText = new StringBuilder();
view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");
msg.AlternateViews.Add(view);
msgText.Append("<body><br></body></html> <br><br><br> " + body);
client = new SmtpClient();
client.Host = "staging.itmaniax.co.za";
client.Send(msg);
k = true;
}
catch (Exception exe)
{
Console.WriteLine(exe.ToString());
}
return k;
}
<system.net>
<mailSettings >
<smtp deliveryMethod="specifiedPickupDirectory" from="ArianG#lr.co.za">
<network host="staging.itmaniax.co.za"/>
<specifiedPickupDirectory pickupDirectoryLocation="C:\testdump\emaildump\"/>
</smtp>
</mailSettings>
I have the feeling the problem lies with the body and the html as it is done with visual studio-2008.
Any advice perhaps?
You can try something like below.
protected void SendMail()
{
// Gmail Address from where you send the mail
var fromAddress = "Gmail#gmail.com";
// any address where the email will be sending
var toAddress = YourEmail.Text.ToString();
//Password of your gmail address
const string fromPassword = "Password";
// Passing the values and make a email formate to display
string subject = YourSubject.Text.ToString();
string body = "From: " + YourName.Text + "\n";
body += "Email: " + YourEmail.Text + "\n";
body += "Subject: " + YourSubject.Text + "\n";
body += "Question: \n" + Comments.Text + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//here on button click what will done
SendMail();
DisplayMessage.Text = "Your Comments after sending the mail";
DisplayMessage.Visible = true;
YourSubject.Text = "";
YourEmail.Text = "";
YourName.Text = "";
Comments.Text = "";
}
catch (Exception) { }
}
For more information check Send Mail / Contact Form using ASP.NET and C#
I hope this will help to you.
it seems that you are missing the:
MailMessage msg = new MailMessage(from, to);
msg.Subject = subject;
msg.Body = body; <--- try adding this and see what happens.
msg.Body property is empty in your example, I guess that's why it doesn't send the body text.

Categories