sending email in asp.net sends password instead of email - c#

I am trying to send email after user has been registered successfully. but it sends password in FROM section instead of sending email like abc#gmail.com here it sends 1234kjfh. what am I missing here?
string name=txtfirstname.Text;
string fileName = Server.MapPath("~/App_Data/TextFile.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", txtfirstname.Text);
mailBody = mailBody.Replace("##Email##", email);
mailBody = mailBody.Replace("##Phone##", txtphone.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Re: Activate your account for AIS FORUM";
myMessage.Body = mailBody;
myMessage.From = new MailAddress("abc#gmail.com", "1234kjfh");
myMessage.To.Add(new MailAddress(txtemail.Text, email));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.EnableSsl = true;
mySmtpClient.Send(myMessage);
Plz help!

The second parameter of the constructor of MailAddress is displayName. You aren't setting the credentials used to send the mail, you are setting the display name.
To set the credentials, use SmtpClient.Credentials:
SmtpClient client = new SmtpClient(server, port);
client.Credentials = new NetworkCredential("username", "password");

You missing something here
new MailAddress(address, displayName)
so, you have added display name as "1234kjfh"
Update your code as follow.
string name=txtfirstname.Text;
string fileName = Server.MapPath("~/App_Data/TextFile.txt");
string mailBody = File.ReadAllText(fileName);
mailBody = mailBody.Replace("##Name##", txtfirstname.Text);
mailBody = mailBody.Replace("##Email##", email);
mailBody = mailBody.Replace("##Phone##", txtphone.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Re: Activate your account for AIS FORUM";
myMessage.Body = mailBody;
myMessage.From = new MailAddress("abc#gmail.com", "abc#gmail.com");
myMessage.To.Add(new MailAddress(txtemail.Text, email));
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.EnableSsl = true;
mySmtpClient.Send(myMessage);
Hope this helps.

Related

Send multiple emails from listbox c#

hi im geting my email list from db in a listbox(email_c) and i need to send to all
this is the error that i get with my code
System.FormatException: 'The specified string is not in the form required for an e-mail address.'
login = new NetworkCredential(txtuser.Text, txtPassword.Text);
client1 = new SmtpClient(txtSmtp.Text);
client1.Port = Convert.ToInt32(txtPort.Text);
client1.Credentials = login;
string emails = email_c.GetItemText(email_c.Items);
msg = new MailMessage { From = new MailAddress(txtuser.Text + txtSmtp.Text.Replace("smtp.", "#"), "Sesizare", Encoding.UTF8) };
msg.To.Add(new MailAddress(emails));
if (!string.IsNullOrEmpty(txtCC.Text))
msg.To.Add(new MailAddress(txtCC.Text));
msg.Subject = txtSubject.Text;
msg.Body = "Abonamentul dumneavoastra a fost activat";
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client1.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userstate = "Ttimite...";
client1.SendAsync(msg, userstate);
The MailAddress does represent the address of an electronic mail sender or recipient. That means it is one single email.
Because of that, instead of writing all the email string into a single string variable you should iterate over the items in the listbox and add each of them individually to the MailMessage. Something like this:
foreach (var email in email_c.Items)
{
msg.To.Add(new MailAddress(email.ToString()));
}

Using System.Net.Mail to send email from Database list of user

I have the following email function that sends an email to a list of users. I add the users with the method message.To.Add(new MailAddress("UserList#email.com")):
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.To.Add(new MailAddress("UserList#email.com"));
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
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(message);
}
But, how can I connect to a SQL-Server Db and get the list of users from a table, instead of from this function? Thanks for the help!
I figured it out myself in the most simple way. I hope this help someone else. Thanks to everybody who responded with positive comments, have the ability to think, and use common sense.
Using System.Net.Mail
protected void SendMail()
{
//Mail notification
MailMessage message = new MailMessage();
message.Subject = "Email Subject ";
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
SqlCommand cmd = null;
string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
string queryString = #"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
cmd = new SqlCommand(queryString);
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
message.To.Add(to);
}
// Passing values to smtp object
smtp.Send(message);
// Call Close when done reading.
reader.Close();
}
}
You could create this utilities.cs file in your current project and paste in the following code and see how much easier it is to read
public class utilities
{
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
}
public static string EmailRecips
{
get
{
return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA#SomeEmail.com|PersonB#SomeEmail.com|Person3#SomeEmail.com"/>
}
}
public static string EmailHost //add and entry in the config file for EmailHost
{
get
{
return ConfigurationManager.AppSettings["EmailHost"];
}
}
public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
{
using (var client = new SmtpClient(utilities.EmailHost, 25))
using (var message = new MailMessage()
{
From = new MailAddress(utilities.FromEmail),
Subject = subject,
Body = body
})
{
//client.EnableSsl = true; //uncomment if you really use SSL
//client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
//client.Credentials = new NetworkCredential(fromAddress, fromPassword);
foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
message.To.Add(address);
client.Send(message);
}
}
}
//if you want to pass a List and join into a single string of Pipe Delimited string to use in the .Split Function then you can change the method signature to take a string and pass in this to the email for example
var emailList = string.Join("|", YourList<T>);
//then the new email function signature would look like this
public static void SendEmail(string subject, string body, string emailList)
//then you would replace the .Split method with this
foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
You can do a lot to optimize and generalize the code below - it's as close to your code as possible while doing what you want. It's up to you to figure out how to connect to your database and get the DataReader.Read(). Try -- if you get stuck, ask something specific.
Using System.Net.Mail
protected void SendMail()
{
Dictionary<string,string> recipients = new Dictionary<string,string>
//--select FirstName, Email form MyClients
//while reader.Read(){
recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
//}
//Mail notification
foreach(KeyValuePair<string,string> kvp in recipients){
MailMessage message = new MailMessage();
message.To.Add(new MailAddress(kvp.Value));
message.Subject = "Hello, "+kvp.Key;
message.Body = "Email Message";
message.From = new MailAddress("MyEmail#mail.com");
// Email Address from where you send the mail
var fromAddress = "MyEmail#mail.com";
//Password of your mail address
const string fromPassword = "password";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.mail.com";
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(message);
}
} //This bracket was outside the code box

Email will not send to large number of people

I have the following code for sending an email alert to around 60 users when an extract gets uploaded. It will send to all the accounts if i am running it locally but when I upload it to the server it doesnt send out any emails, not unless its only to one person. I dont have much experience with hosting and server stuff so any help you can give me would be great.
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Connection String (SendEmail)
string SendEmail = ConfigurationManager.ConnectionStrings["Sendmail"].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.ac.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.ac.uk", "PTLP"); //address and from name
smtpclient.Host = "omavex011"; //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 Payroll details are now available for checking.</p> ";
//smtpclient.EnableSsl = true;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
smtpclient.Send(mail);
}
}
}
As mentioned in my comment this is how you would use a single SmtpClient instance:
if (Session["ExtractNo"].ToString() == "Extract 1")
{
//Email Config
const string username = "roll#test.ac.uk"; //account address
const string password = "######"; //account password
SmtpClient smtpclient = new SmtpClient();
smtpclient.Host = "omavex011";
smtpclient.Port = 25;
smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpclient.Credentials = new System.Net.NetworkCredential(username, password);
string SendEmail = ConfigurationManager.ConnectionStrings["Sendmail"].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)
{
MailMessage mail = new MailMessage();
MailAddress fromaddress = new MailAddress("roll#test.ac.uk", "PTLP"); //address and from name
mail.From = fromaddress;
mail.To.Add(email.Email);
mail.Subject = ("PTLP Check");
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlEncode(email.Name) + " <br /> <p>Part Time Payroll details are now available for checking.</p> ";
smtpclient.Send(mail);
}
}
smtpclient.Dispose();
}

Unable to send the mailmessage in asp.net

The following code unable to send an emails to customers and it not throwing any exception. The code it not send any email or exception but executed.I am completely new about the asp.net. Some one can help me how to resolve the problem.
Code:
try
{
String userName = "ramesh";
String passWord = "123456";
String sendr = "ramesh#gmail.com";
String recer = "customer#yahoo.com";
String subject = "Comformation ";
String body = "Dear Customer";
MailMessage msgMail = new MailMessage(sendr, recer, subject, body);
int PortNumber = 25;
SmtpClient smtp = new SmtpClient("smtp.test.com", PortNumber);
msgMail.IsBodyHtml = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(userName, passWord);
smtp.Send(msgMail);
MsgLP.Text = "Emailed to Customer..";
LogInLink.Visible = true;
}
catch (Exception ex){
AuditLog.LogError("ErrorE-mail " + ex.Message);
}
You have to set smtp.EnableSsl=true and use port number 587. Your final code will be this:
try
{
String userName = "ramesh";
String passWord = "123456";
String sendr = "ramesh#gmail.com";
String recer = "customer#yahoo.com";
String subject = "Comformation ";
String body = "Dear Customer";
MailMessage msgMail = new MailMessage(sendr, recer, subject, body);
int PortNumber = 587; //change port number to 587
SmtpClient smtp = new SmtpClient("smtp.gmail.com", PortNumber); //change from test to gmail
smtp.EnableSsl = true; //set EnableSsl to true
msgMail.IsBodyHtml = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential(userName, passWord);
smtp.Send(msgMail);
MsgLP.Text = "Emailed to Customer..";
LogInLink.Visible = true;
}
catch (Exception ex){
AuditLog.LogError("ErrorE-mail " + ex.Message);
}
I tested this code with my credentials and it works fine.
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
mm.From = new MailAddress("email#gmail.com");
mm.To.Add("email#gmail.com");
System.Net.Mail.Attachment attachment;
string strFileName;
strFileName = "Uploadfile/" + "200814062455PM_Admin_Screenshot (10).JPEG";
attachment = new System.Net.Mail.Attachment(Server.MapPath(strFileName));
mm.Attachments.Add(attachment);
mm.Body = ("<html><head><body><table><tr><td>Hi</td></tr></table></body></html><br/>"); ;
mm.IsBodyHtml = true;
mm.Subject = "Candidate " + Name + " for your Requirement " + Jobtt + " ";
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("email#gmail.com", "password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
object userstate = mm;
client.Send(mm);

Edit HTML Email template at run time in .net code

I below code is to send email by reading the template html, and it works fine. But now my question is how to pass Salutation customerName from my .net code to the template at run time.
StringBuilder strBlr = new StringBuilder();
string strHTML = string.Empty;
string strTempalteHtmlpath = string.Empty;
//create the mail message
MailMessage mail;
string strFrom = ConfigurationSettings.AppSettings["fromAddressForBT"];
string strSubject = "Thanks for choosing Email contact preference";
mail = new MailMessage(strFrom, customerDetails.EmailId);
mail.Subject = strSubject;
//Read Html Template File Path
strTempalteHtmlpath = Convert.ToString(ConfigurationSettings.AppSettings["TemplatePath"]);
strHTML = File.ReadAllText(strTempalteHtmlpath);
strBlr = strBlr.Append(strHTML);
mail.Body = strBlr.ToString();
mail.IsBodyHtml = true;
//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strBlr.ToString(), null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
SmtpClient smtpMail = new SmtpClient(ConfigurationSettings.AppSettings["smtpClient"]);
smtpMail.Send(mail);
mail.Dispose();
Thanks.
This is code for sendemail button
StreamReader sr = new StreamReader(Server.MapPath("Sendpage.htm"));
string body = sr.ReadToEnd();
sr.Close();
body = body.Replace("#NameFamily#", txtNameFamily.Text);
body = body.Replace("#Email#", txtEmail.Text);
body = body.Replace("#Tellphone#", txtTellphone.Text);
body = body.Replace("#Text#", txtText.Text);
body = body.Replace("#Date#", DateTime.Now);
string Time = Convert.ToString(DateTime.Now.ToShortTimeString());
body = body.Replace("#Time#", Time);
SendMail("email that you want to send to it", body);
this is sendmail function code:
private void SendMail(string To, string Body)
{
SmtpClient Mailing = new SmtpClient("mail.domain.com");
MailMessage Message = new MailMessage();
Message.From = new MailAddress("mail#domain.com", "Your name or company name");
Message.Subject = "Subject";
Message.SubjectEncoding = Encoding.UTF8;
Message.IsBodyHtml = true;
Message.BodyEncoding = Encoding.UTF8;
Message.Body = Body;
Message.To.Add(new MailAddress(To));
Mailing.UseDefaultCredentials = false;
NetworkCredential MyCredential = new NetworkCredential("mail#domain.com", "password");
Mailing.Credentials = MyCredential; Mailing.Send(Message);
}

Categories

Resources