Sending e-mail in asp with usings - c#

I have an email form on my website which is working great. The only thing I want to do is add usings for better coding, what is the best way to do this? The code I use is the following:
try
{
//create message
MailMessage msg = new MailMessage();
msg.To.Add(txtTo.Text);
msg.From = new MailAddress(txtFrom.Text);
msg.Subject = string.Format("Van: " + txtName.Text + " | Email: " + txtFrom.Text + " | Onderwerp: " + txtSubject.Text);
msg.Body = txtBericht.Text;
SmtpClient smtp = new SmtpClient("");
smtp.Host = "smtp.live.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("emailaddress", "pass");
smtp.Send(msg);
ClearTextboxes();
lblError.ForeColor = Color.Green;
lblError.Text = "Het verzenden van uw e-mail is gelukt!";
}
catch
{
lblError.ForeColor = Color.Red;
lblError.Text = "Er ging iets mis met het versturen van de email.";
}
How can I use usings on this code?
And is it safe to use fill in my emailaddress and password when I'm uploading my website, or should I use another method?
Thanks in advance!
EDIT:
I changed my code to the following:
try
{
//create message
using (MailMessage msg = new MailMessage())
{
//create message
MailMessage msg = new MailMessage();
msg.To.Add(txtTo.Text);
msg.From = new MailAddress(txtFrom.Text);
msg.Subject = string.Format("Van: " + txtName.Text + " | Email: " + txtFrom.Text + " | Onderwerp: " + txtSubject.Text);
msg.Body = txtBericht.Text;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.live.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("emailadress", "pass");
smtp.Send(msg);
}
ClearTextboxes();
lblError.ForeColor = Color.Green;
lblError.Text = "Het verzenden van uw e-mail is gelukt!";
}
}
catch
{
lblError.ForeColor = Color.Red;
lblError.Text = "Er ging iets mis met het versturen van de email.";
}

Never put authentication information in your code. Put it in your web.config instead and reference it where you need it. That also saves you the trouble of hunting down everywhere you used it if you change your password.

I would suggest using the web.config for setting up the host, username and password. Example.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="name#domain.com">
<network host="smtp.mail.com"
userName="name#domain.com"
password="blog.dotnetclr.com" port="25"/>
</smtp>
</mailSettings>
</system.net>
Code Example:
Public Sub SendEmail([to] As String, subject As String, body As String)
Dim mailMessage = New System.Net.Mail.MailMessage()
mailMessage.[To].Add([to])
mailMessage.Subject = subject
mailMessage.Body = body
Dim smtpClient = New SmtpClient()
smtpClient.EnableSsl = True
smtpClient.Send(mailMessage)
End Sub

http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.100).aspx
using (MailMessage msg = new MailMessage())
{
//Your Code
}

You could use using for both MailMessage and SMTP Client objects
//create message
using (SmtpClient smtp = new SmtpClient(""))
using( MailMessage msg = new MailMessage())
{
// Your code
}

using(SmtpClient smtp = new SmtpClient()){
//smtp options here
using(MailMessage msg = new MailMessage()){
//mail options here
smtp.Send(msg);
}
}

Related

Gmail mail cannot be sent through C#

I have created a Windows application which is used to send emails. i have given credentials. i turned on google/settings/lesssecure apps. Eventhough its not sending. Its showing the error The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required here is my code.
MailMessage message = new MailMessage();
message.From = new MailAddress("Selvacsebe23#gmail.com");
string[] mailaddress = new string[count];
int i;
if (textSubject.Text != string.Empty)
{
message.Subject = textSubject.Text;
if (textBody.Text != string.Empty)
{
message.To="Selvakesavan#gmail.com"
message.IsBodyHtml = true;
string tmpBody = "Hello " + "," + "<br/> <br/>" + textBody.Text + "<br/> <br/>" + "Thanks and Regardds";
message.Body = tmpBody;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("selvacsebe23#gmail.com", "mypassword");
message.Priority = MailPriority.High;
client.EnableSsl = true;
client.Send(message);
MessageBox.Show("Mail has sent successfully !!!", "Success !");
}
else
{
MessageBox.Show("Please Enter Body of the Message !");
}
}
else
{
MessageBox.Show("Please Enter Subject !");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Failure !");
log.Fatal(ex.Message);
}
}
If you turn on 2-step-verification, then you need to login using app-specific-password. You can create it here:
https://support.google.com/accounts/answer/185833?hl=en. If you use your normal password, then you will get exception : 5.5.1 Authentication Required. You don't need lots of code, this code is enough to send email without attachment:
const string from = "user1#gmail.com";
const string to = "user2#yahoo.com";
const string subject = "This is subject";
const string body = "This is body";
const string appSpecificPassword = "akdfkajsdhklakdfh";
var mailMessage = new MailMessage(from, to, subject, body);
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.Credentials = new NetworkCredential(from, appSpecificPassword);
smtpClient.Send(mailMessage);
}

Send mail from Exchange Server

I want to send mail from exchange server without password. I use the following code snippet :
MailMessage msg = new MailMessage();
msg.From = new MailAddress("kavitham#test.com");
msg.To.Add(new MailAddress("kavitham#sample.com"));
msg.Subject = "Reg : Mail test";
msg.IsBodyHtml = true;
msg.Body = "<html><body>" + strMsg + "</body></html>";
SmtpClient client = new SmtpClient("IP of Server", 25);
client.Host = "IP of Server";
client.Send(msg);
But the mail is not sent. Is there any other settings for Exchange server need to be done ?
add this
smtpClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
MailMessage msg = new MailMessage("noreply#test.com", "manager#test.com", "Notification For Lead / Admin ",
"Emp Name :" + EmpName);
msg.Body = "Emp Name : " + EmpName + "<br /><br >" + Environment.NewLine + timsheetMail;
msg.IsBodyHtml = true;
msg.CC.Add(toMail); msg.CC.Add(admin);
SmtpClient SMTPServer = new SmtpClient("mail.myserver.com", 25);
SMTPServer.Timeout = 300000;
SMTPServer.EnableSsl = false;
SMTPServer.Credentials = new System.Net.NetworkCredential("noreply#test.com", "passw0rd");
SMTPServer.Send(mailObj);

Failure sending e-mail in asp.net

Here's my code. I know that this is a duplicate question but I have visited all the links in staqckoverflow and codeproject but still I am unable to get an answer.
try
{
MailMessage mailmessage = new MailMessage();
mailmessage.To.Add("xxx.com");
mailmessage.From = new MailAddress("xxx.com");
mailmessage.Subject = "Transaction sent for Verification ";
mailmessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!";
SmtpClient smtpClient = new SmtpClient(ConfigurationSettings.AppSettings["SmtpAdd"].ToString());
smtpClient.Send(mailmessage);
ClientScript.RegisterStartupScript(this.GetType(), "mailalert", "alert('" + "Mail sent for verification" + "');", true);
}
catch(Exception ex)
{
//Response.Write("Could not send E-mail- error: " + ex.Message);
ClientScript.RegisterStartupScript(this.GetType(), "mailfailure", "alert('" + ex.Message + "');", true);
}
This will help you
MailMessage msg = new MailMessage();
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("To_address"));
msg.Subject = "You have a WebMail!!";
msg.IsBodyHtml = true;
msg.Body = "Message";
SmtpClient smtp = new SmtpClient();
smtp.Credentials = new NetworkCredential("your mail address", "your password");
smtp.Host = "host name";
smtp.Port = "host number";
smtp.EnableSsl = false;
smtp.Send(msg);

Hyperlinks in mails not showing in gmail, but it does in Outlook

I've got a c# process that send emails to customers with a hyperlink in the mail. The mail is send from a SQL Server stored proc. My c# program just invokes the sp.
The hyperlink works fine in Outlook, but on online gmail it only shows as text. It is not clickable.
My mail text looks something like:
Hi.
This is the hyperlink:<br>
<a href=\"serveraddress\Documents\\123_128635312685687531322.gif\">
Click Here</a><br><br>
What should I do to fix it?
EDIT:
My code:
string email = "xx#gmail.com;
string password = "MyPassword";
var credentials = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email, senderName);
msg.To.Add(new MailAddress(toAddress));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = credentials;
smtpClient.Send(msg);
EDIT 2:
Compile message being send:
string message = #"Hi. <br>
This is the intro line in the mail message.<br>";
using (DataTable dtLinks = data.ExecuteDataSet(#"SELECT *
FROM LessonFiles
WHERE Course = " + dr["Course"].ToString().DBValue() + #" AND
Lesson = " + dr["NextLesson"].ToString().DBValue()).Tables[0])
{
int i = 0;
foreach (DataRow drLink in dtLinks.Rows)
{
i += 1;
message += "<a href=\"" + drLink["Link"].ToString() + "\">" + drLink["Lesson"].ToString();
message += i == 1 ? "" : " file " + i;
message += "</a>" + "<br>";
}
}
message += "<br>Regards<br><br>";
try to add target="_blank", like this...
message += "<a href=\"" + drLink["Link"].ToString() + "\"target=\"_blank\">" + drLink["Lesson"].ToString();
Seems like something was funny with the hyperlink itself.
Using http://serveraddress/Documents/logoColourBG635315550177822533.jpg seems to work.
The original contained backslashes in the path. The fact that it showed the hyperlink in Outlook led me to believe the address was correct.
Thanks for all your help.
creating mail message object...
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(UserName, Password);
smtp.Timeout = 20000;
MailMessage Msg = new MailMessage();
Msg.IsBodyHtml = true;
MailAddress fromMail = new MailAddress(SenderID);
Msg.From = fromMail;
Msg.To.Add(new MailAddress(TosendID));
Msg.Subject = subject;
Msg.Body = body;
In body add ur code.....
Hope This Helps.........

sending email fails in C# 3.5

While sending email, I get the following error:
The device is not ready at System.Net.Mail.SmtpClient.Send(MailMessage message).
The code is :
MailMessage mailMessage = new MailMessage(senderEmail, cleanRecipients)
{
Subject = string.empty,
Body = string.empty,
IsBodyHtml = false
};
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
In order to send an email you need an SMTP server, so make sure you have specified an SMTP server in the config file.
<system.net>
<mailSettings>
<smtp from="someaddress#mydomain.com">
<network host="mail.mydomain.com" password="secret" port="25" userName="someaddress#mydomain.com" />
</smtp>
</mailSettings>
</system.net>
This code maybe will help!
string from = me#gmail.com; //Replace this with your own correct Gmail Address
string to = you#gmail.com //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
HttpContext.Current.Response.Write(errorMessage );
} // end try

Categories

Resources