Send mail stored in a variable - c#

I have a simple table(MyEmail) in SQL with some emails that need to be sent, for example:
ID Email
1 name#yahoo.com
2 something2#yahoo.com
3 name3#google.com
4 something4#yahoo.com
I made a stored procedure(GetAddress) to collect them so I can later store them into a variable:
SELECT Email
FROM dbo.MyEmai
I need help with the C# part of the code:
var MyEmails = new List<Email>();
SqlCommand cmdEmails = new SqlCommand("GetAddress", connection);
SqlDataReader rdEmails = cmdEmails.ExecuteReader();
while (rdEmails.Read())
{
MyEmails.Add(new Email() { MyEmails = rdEmails[0].ToString() }); // as an example
}
This code returns list but emails are located bellow WebApplication.MyPage.
Email names.
MyEmails return :
WebApplication.MyPage.Email > name#yahoo.com
WebApplication.MyPage.Email > something2#yahoo.com ...
And I need this WebApplication.MyPage.Email removed so only emails will be shown as strings first.
Code that sends emails:
SmtpClient client = new SmtpClient();
client.Port = 112;
client.Host = "my-smtp";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("myEmail#provider.com", "");
MailMessage mm = new MailMessage(LocalName, LocalName + MyEmails, "New Mail subject", "This is Email body !");
client.Send(mm);
So because of this MyEmails has an error : Error 24 Argument 2: cannot convert from 'System.Collections.Generic.List' to 'string'
Can someone help me with this?
Thanks in advance!

The MailMessage class from .Net does not accepts a List as a valid parameter. Iiterate over your collection creating multiple mailmessage.
The code should look something like this
foreach (var emailadressObject in myEmails)
{
// get your emailadres string from your object..
// Bit confusion using a collection MyEmails and a Property in you mail objetc with MyEmails
var emailadresstring = emailadressObject.MyEmails;
var message = new MailMessage("from#me.com", emailadresstring, "New Mail subject", "This is Email body !");
// Do you magic with the mail message
}

Related

C# MVC Send email to multiple recipient

I have trying to send one mail to Test1 and Test2. I tried separating the recipients with ; like To ="Test1#stanleytests.co.za;Test2#stanleytests.co.za" that did not work and also tried concatenating them by doing To="Test1#stanleytests.co.za"+"Test2#stanleytests.co.za" that did not work. now I wrote and Array. the thing with my array is that it sends 2 mails, so i only want to sent one mail to two recipient.
private void SendDailyEmails(DateTime today)
{
today = DateTime.Now;
string recipient = "Test1#stanleytests.co.za,Test2#stanleytests.co.za";
string[] emailTo = recipient.Split(',');
for (int i = 0; i < emailTo.GetLength(0); i++)
{
var emailObject = new EmailObject
{
To = emailTo[i],
Cc = "me#stanleytests.co.za",
Subject = "Daily Mail",
Body = "Good morning, <br/><br/> This email is sent to you: <strong> "please be adviced" </strong> <br/><br/>Regards"
};
_emailService.SendEmail(emailObject);
}
}
Please assist here.thanks
Partially your code, see the example below. Honestly, I don't have access to our SMTP servers here, so, I can't really test it. This should set you on the right path. I am guessing your issue really is that you are missing: new MailAddress(i) .
Hope this helps, there are more reference material on MSDN's site.
private void SendDailyEmails()
{
var today = DateTime.Now;
var recipient = "Test1#stanleytests.co.za,Test2 #stanleytests.co.za";
var message = new MailMessage()
{
From = new MailAddress("Somebody"),
CC = { new MailAddress("me#stanleytests.co.za") },
Subject = "Daily Mail",
Body = #"Good morning, <br/><br/> This email is sent to you: <strong> ""please be adviced"" </strong> <br/><br/>Regards",
IsBodyHtml = true
};
foreach (var i in recipient.Split(',').ToList())
{
message.To.Add(new MailAddress(i));
}
// do your "_emailService.SendEmail(message);
}
We don't know what library you are using for sending emails thus I can only make suggestions.
The convention for joining several email address is to separate them with ; :
emailObject.To = String.Join(";", recipient.Split(','));
string body = "Body of email";
var message = new MailMessage();
message.To.Add(new MailAddress("example#exaple.com"));
message.To.Add(new MailAddress("example2#exaple.com"));
message.From = new MailAddress("example#gmail.com", "Name");
message.Subject = "This is the subject";
message.Body = body;
message.IsBodyHtml = true;

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

cannot convert from 'object' to 'System.Net.Mail.MailMessage'

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

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