cannot convert from 'object' to 'System.Net.Mail.MailMessage' - c#

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

Related

Forgot Password in windows form c#

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.

C# Send email using Office 365 SMTP doesn't change given email display name

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

set body as html when sending email c# [duplicate]

This question already has answers here:
How to send HTML-formatted email? [duplicate]
(3 answers)
Closed 5 years ago.
I am calling a function that sends an email in my asp.net mvc project and I want the body to be able to format as html
Here is my function that sends the email :
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
The email is sent and it works like a charm, but It just shows plain html so I was wondering an argument in my instanciation of MailMessage
You just need to add the parameter IsBodyHtml to your instanciation of the MailMessage like this :
private bool EnvoieCourriel(string adrCourriel, string corps, string objet, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = objet,
Body = corps,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
try
{
msg.To.Add(adrCourriel);
smtp.Send(msg);
}
catch(Exception e)
{
var erreur = e.Message;
return false;
}
return true;
}
I also added a try catch because if there is a problem when trying to send the message you can show an error or just know that the email was not sent without making the application crash
I think you are looking for IsBodyHtml.
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}

C# email alert not picking up new code

I have following code for sending an email alert to around 60 users when an extract gets uploaded. However something strange is happening, it is sending to the previous query results not the new ones. The only difference is the quantity of users before it was sending to only a few people now its sending to a larger quantity. But on the code with larger quantity the application seems to not see that it has changed and sends to previous users. Like its cached the query or something. I don't know whats going on. But when I do change it to just one email address it works fine and picks up changes.
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Connection String (SendEmail)
string SendEmail = ConfigurationManager.ConnectionStrings["SendEmail"].ConnectionString;
SqlDataReader reader;
String SendMessage = "SELECT Name, Position, Email FROM AuthorisedStaff Where Position = 'CM' or Position = 'DHOD' or Position = 'HOD'"; //<---- change position before launch
using (SqlConnection myConnection = new SqlConnection(SendEmail))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(SendMessage, myConnection);
ArrayList emailArray = new ArrayList();
reader = myCommand.ExecuteReader();
var emails = new List<EmailCode>();
while (reader.Read())
{
emails.Add(new EmailCode
{
Email = Convert.ToString(reader["Email"]),
Name = Convert.ToString(reader["Name"]),
Position = Convert.ToString(reader["Position"])
});
}
foreach (EmailCode email in emails)
{
//Email Config
const string username = "roll#test.co.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.co.uk", "PTLP"); //address and from name
smtpclient.Host = "omavex11"; //host name for particular email address
smtpclient.Port = 25; //port number for particular email address
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
//change context of message below as appropriate
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Lecturer Payroll details are now available for checking. If any changes need made please notify MIS as soon as possible. </p> <p>Please ensure all Adjustments have also been submitted. All Adjustments not submitted on time will be paid the following month. </p> ";
//smtpclient.EnableSsl = true;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
}
}
}
Try clearing the list first before adding new items/objects
I assume that this
var emails = new List<EmailCode>();
is the list.

Getting email address from text box and send it

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)

Categories