if (txtEmail.Text != null)
{
try
{
SmtpClient sc = new SmtpClient("localhost", 587);
sc.Host = "smtp.gmail.com";
sc.Credentials = new NetworkCredential("MyEmail#gmail.com",
"MyPassword");
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.EnableSsl = true;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("MyEmail#gmail.com");
mailMessage.Subject = "Sending Test";
mailMessage.Body = "this is a test message your UserName is"
+ txtUserName.Text;
mailMessage.IsBodyHtml = true;
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
sc.Send(mailMessage);
lblMessage.Text = "Mail send...";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
else
{
lblMessage.Text = "you should enter your email address";
}
Alright first of all sorry about my weak English language, however i read lots of articles about how to send an E-mail with C# and i know how to do it...
But my problem is when I want to send E-mail that entered to a text box and I put for example
(E-mailAddress.text) into a MailAddress or MailMessage.Add,
it threw me an exception that says
(The parameter 'addresses' cannot be an empty string. Parameter name: addresses)
and shows me the MailAdress or MailMessage object that filled with E-mailAddress.text instead with a string like "abc#yahoo.com" and even in further i'm not capable to send the E-mail ... if there is any help i'd be so glad
First i would change
txtEmail.Text != null
to
!string.IsNullOrEmpty(txtEmail.Text)
Then i would try to do it this way:
mailMessage.To.Add(new MailAddress(txtEmail.Text.Trim()));
instead of
string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);
Also i would implement a method to validated the entered email address to avoid invalid addresses :)
Check for:
if (txtEmail.Text.Trim() != String.Empty)
instead of
if (txtEmail.Text != null)
Related
In the code below: I want to warn a user when he/she tries to enter an email which is (is not) associated with the database. When I type something is not in my database, it says "Your record is not in our database". But when I enter a valid email it says: input string was not in a correct format
so this line code doesnt work: smtpClient.Send(message);
string randomCode = "";
public static string to;
public ForgotPassword()
{
InitializeComponent();
}
private void btn_EmailSend_Click(object sender, EventArgs e)
{
string from, pass, messagebody;
#region Generating random code
Random ran = new Random();
string randText = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
int Length_randText = randText.Length;
for (int i = 0; i < 5; i++)
{
randomCode += randText[ran.Next(Length_randText)];
}
#endregion
MailMessage message = new MailMessage();
to = txt_Email.Text;
from = "------";
pass = "------";
messagebody = "You have requested to reset your password. Enter this \"" + randomCode + "\" - code to change your password";
message.To.Add(to);
message.From = new MailAddress(from);
message.Body = messagebody;
message.Subject = "Password resetting request";
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential(from, pass);
try
{
using (DALC.GetConnection())
{
SqlCommand cmd = new SqlCommand("select email from loginuser where email = '" + to + "'", DALC.con);
object result = cmd.ExecuteScalar();
if (Convert.ToInt16(result)>0)
{
smtpClient.Send(message);
MessageBox.Show("I have sent your resetting code to you email. Check your inbox :)", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Your record is not in our database");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You actually shouldn't do that, this is considered bad practice. A malicious user should never be able to guess a valid Email address (which in your case he would be able to).
You should only give the user an Email with a password-reset if he/she enters their Email address correctly. Even if the Email address is not in your database only a message without data-leakage should appear, i.e. "An Email to reset your password has been sent to your address".
The same issue should be applied to a login: If the login fails a user should only receive a message that doesn't distinguish from the name / password, something like "You have entered an invalid username or password".
See also this question for more information.
I am using C# MailMessage for sending Email through office 365, and I want to change the display name of the sender in the email.
I have tried using mailMessage MailAddress Constructor like this
mailMessage.From = new MailAddress("email","display name");
but it doesn't solve the problem
But when I tried to use Gmail instead, the display name is changed.
This is our generic SMTP email function. It includes the sender's email address and name.
public static bool EmailReport(
String Subject,
String Body,
String FromAddress,
String FromName
String[] To,
String[] CC,
out String sError)
{
MailMessage m = new MailMessage();
SmtpClient smtp = new SmtpClient("<insert your email server name here i.e.: mail.Mycompany.com>");
smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
m.Subject = Subject;
m.Body = Body;
m.From = new MailAddress(FromAddress, FromName);
foreach (String sTo in To)
{
m.To.Add(sTo);
}
if (CC != null)
{
foreach (String sCC in CC)
{
m.CC.Add(sCC);
}
}
try
{
smtp.Send(m);
sError = "";
return true;
}
catch (Exception ex)
{
sError = ex.Message + "\r\n\r\n" + ex.StackTrace;
return false;
}
}
I am cracking my head to find a solution for that strange behavior.
I have made a lot of tests and experiments and tried to play around with my code but with no success.
Server: Windows service on windows server 2012 .net framework 4.0.
Client: windows 7 os, outlook 2010.
Problem: html tags and \ or attributes inside the message body are affecting client from receiving emails and no exception is thrown on the server.
there are several cases that html inside the body message is preventing from the client to receive email to his outlook inbox.
Example: if i am calling SendHtmlEmail() like that everything works fine as expected:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl><br/>test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
but if i am removing the <br/> tag, the client is not receiving email and no exception is thrown:
Exchange.InvokeEmail.SendHtmlEmail("testTrue", "<div dir=rtl> test</div>", "jonathana#xxx.net",null, "מערכת ניהול פרויקטים", null,true);
another example is using the dir attribute:
"<body dir=rtl> test </body>" // not working
"<body ><br/>test</body>" // working
"<div dir=rtl> test </div>" // not working
"<div ><br/>test</div>" // working
I have tried to change Encoding of the body but nothing helps. also, because no exception is raised I assume the problem is on client side(?) (outlook 2010, windows 7 os).
Thank you.
Server code:
public static bool SendHtmlEmail(string _subject, string _body,
string _to, string _cc = null,
string _DisplayName = "מערכת ניהול פרויקטים", string _FileName = null,bool Isanonymous = true)
{
try
{
MailMessage msg = new MailMessage();
// from
if (Isanonymous == false)
msg.From = new MailAddress("pmsapp#partner.co.il");
else
msg.From = new MailAddress("PmsApplication#partner.co.il", _DisplayName);
// to
foreach (var address in _to.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.To.Add(address);
}
// cc
if (_cc != null && _cc.Contains("#"))
{
foreach (var address in _cc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.CC.Add(address);
}
}
msg.Subject = _subject;
msg.Body = _body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
if (Isanonymous==false)
client.Credentials = new System.Net.NetworkCredential("xxxxx", "xxxxxxx");
client.Port = 25;
client.Host = ConfigurationManager.AppSettings["Exchange.SmtpServerName"];
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
return true;
}
catch (Exception ex)
{
string error = ex.ToString(); // TODO: write to database
return false;
}
}
What is going wrong?
I am trying to send an email but I'm getting the error in the title of the question. why doesn't an object be converted to a 'System.Net.Mail.MailMessage'.
private object message;
protected void btnSend_Click(object sender, EventArgs e)
{
String TMess = txtMessageBody.Text;
String TEmail = txtEmail.Text;
String TSub = txtSubject.Text;
//this particular email server requires us to login so
//create a set of credentials with the relevent username and password
System.Net.NetworkCredential userpass = new System.Net.NetworkCredential();
userpass.UserName = "email";
userpass.Password = "password";
//ensure the smtp client has the newly created credentials
client.Credentials = userpass;
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
}
else
{
//create a new email from REPLACE_WITH_USER#gmail.com to recipient#domain.com
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
}
//set the subject of the message, and set the body using the text from a text box
message.Subject = txtSubject.Text;
message.Body = txtMessageBody.Text;
//send the message
client.Send(message);
//clear the message box
//the email has been sent - either by displaying a message (e.g. a literal) or by redirecting them to a 'Message sent' page
txtMessageBody.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
}
var client = new SmtpClient();
var message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
var subject = txtSubject.Text;
var body = txtMessageBody.Text;
message.Subject = subject;
mail.Body = body;
client.Send(message);
At the absolute minimum this should work just fine. Try adding your other code one line at a time and see where it breaks.
the problem lies in your if else loop. If it goes to the if statement ( and not the else statement) your mailmessage object doesn't exist. something that doesn't exist can't be parsed.
you can do it like this
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
return;
}
Hello I'm building a new site. But my usual mail code working only sometimes with this site.I was able to send mail within 01.00 - 01.10 and get a error "Failure to send mail" for 15 minutes.And now I'm able to send again. Its probably a issue with my hosting firm but can you review the code just to be safe? Thanks in advance.
[HttpPost]
public string processData(PersonDTO p)
{
try
{
var bdy = string.Format("Alınacak Yer: {0}\nAd Soyad: {1}\nTarih: {2}\nSaat: {3}\nBırakılacak Yer:{4}\nEmail: {5}\nUçuş No: {6}\nTelefon: {7}\nAdres Tarifi: {8}\nYolcu Sayısı: {9}", p.PickupSite, p.Name, p.Date, p.Time, p.DropSite, p.Email, p.FlightNumber, p.Phone, p.AddressLocation, p.NumberOfPassengers);
var msg = new MailMessage();
msg.From = new MailAddress("system#globalairporttransfer.com");
msg.To.Add("info#globalairporttransfer.com");
msg.Subject = "Yeni Istek";
msg.Body = bdy;
msg.IsBodyHtml = false;
var client = new SmtpClient("mail.globalairporttransfer.com", 25);
client.Credentials = new NetworkCredential("system#globalairporttransfer.com", "mypasswordishere");
client.EnableSsl = false;
client.Send(msg);
return "Kaydınız alındı. En kısa sürede ileşime geçeceğiz.";
}
catch (SmtpException e){return "Mesaj Gönderilemedi ! Hata Mesajı: \n" +e.Message;}
catch (SocketException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
catch (FormatException e) { return "Mesaj Gönderilemedi ! Hata Mesajı: \n" + e.Message; }
}
}
After fighting several hours with my hosting firm I proved that there is a problem with their end. After some configuration from their end I noticed Dns couldnt be resolved. If you have that problem you can try write ip adress of smtp instead of name.. I hope it helps some
var client = new SmtpClient("Ip of the smtp server", 25);