Sending Email in ASP.NET without Logging in - c#

In my search for a way to send email on my webapp through a form, the only solution I got working was an old MSDN solution for a WebMail helper where it had me hardcode the credentials for an email to send through.
Right, off the bat, I know this is not ideal. Is there an easy way to send this mail out from a WebMail default so I can remove the login credentials and not look so amateurish???
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var customerPhone = Request["customerPhone"];
var customerRequest = Request["customerRequest"];
var errorMessage = "";
var toMail = "user#mail.com";
var debuggingFlag = false;
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.SmtpPort = 587;
WebMail.UserName = "user#mail.com";
WebMail.Password = "Password!";
WebMail.From = "user#mail.com";
WebMail.EnableSsl = true;
// Send email
WebMail.Send(to: toMail,
subject: "Quote/Info request from - " + customerName,
body: customerPhone + customerRequest
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}

See the mailSettings element of you web.config file.
For some reason the msdn page on the WebMail class recommends the _AppStart.cshtml file as a suitable place to configure these settings.

Related

C# SmtpException - problem with sending mails

Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...
When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s
Here's the code:
protected void SendMessage(object sender, EventArgs e)
{
// receiver address
string to = "******#student.uj.edu.pl";
// mail (sender) address
string from = "******#gmail.com";
// SMTP server address
string server = "smtp.gmail.com";
// mail password
string password = "************";
MailMessage message = new MailMessage(from, to);
// message title
message.Subject = TextBox1.Text;
// message body
message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;
SmtpClient client = new SmtpClient(server, 587);
client.Credentials = new System.Net.NetworkCredential(from, password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
try
{
client.Send(message);
// ui confirmation
TextBox3.Text = "Wysłano wiadmość!";
// disable button
Button1.Enabled = false;
}
catch (Exception ex)
{
// error message
TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
}
}
I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?
Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.
Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.
void Main()
{
UserCredential credential;
using (var stream =
new FileStream(#"C:\credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels = request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
//Console.Read();
var msg = new Google.Apis.Gmail.v1.Data.Message();
MimeMessage message = new MimeMessage();
message.To.Add(new MailboxAddress("", "toemail.com"));
message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere#gmail.com"));
message.Subject = "Test email with Mime Message";
message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
var ms = new MemoryStream();
message.WriteTo(ms);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string rawString = sr.ReadToEnd();
byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
msg.Raw = System.Convert.ToBase64String(raw);
var res = service.Users.Messages.Send(msg, "me").Execute();
res.Dump();
}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";
Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.
Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.

how to do attachments from a specific directory when sending an email

So I'm trying to add an attachment when I send an email, but I am not sure how. The email works perfectly fine, but it's the adding onto the attachment for the email which doesn't work. I'm not trying to use any specific platform and just sending it via through the console essentially. I tried msgObj.attachments1.add(...) but it didn't work with it.
using (SmtpClient client = new SmtpClient("10.10.101.10", 500))
{
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(username,password);// has username and password credentials doesnt contain actual username and pass
MailMessage msgObj = new MailMessage();
List<string> attachments1 = new List<string>();
attachments1.Add(#"C:\Users -test.xlsx");
msgObj.IsBodyHtml = true; //always sets true, if the body contains html it turns text to html
msgObj.To.Add(Destination);
msgObj.From = new MailAddress("test#mail.com"); //you can send emails on behalf of somebody
msgObj.Subject = YourMessageSubject;
// msgObj.Body = YourMessageBody; //need to edit the body remember to use the message body to call upon it
msgObj.Body = messageBody2; //html
client.Send(msgObj); // sends the message
}
}
catch (Exception)
{
Console.WriteLine("somethings broken");
}
Try attaching it:
msgObj.Attachments.Add(new Attachment(#"C:\Users -test.xlsx"));

Sending email in C#

I am working on a page where I have to send an email in C#.
I followed the codes on
http://blogs.msdn.com/b/mariya/archive/2006/06/15/633007.aspx
and came upon this two exceptions
A first chance exception of type 'System.Net.Mail.SmtpException' occurred in System.dll. A first chance exception of type
'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Here are the codes I implemented. I can't seem to figure what went wrong.
//Send email notification - removed actual email for this question
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
MailAddress from = new MailAddress("myemail#gmail.com", "My name is here");
MailAddress to = new MailAddress("anotherpersonsemail#gmail.com", "Subject here");
MailMessage message = new MailMessage(from, to);
message.Body = "Thank you";
message.Subject = "Successful submission";
NetworkCredential myCreds = new NetworkCredential("myemail#gmail.com",
"mypassword", "");
client.Credentials = myCreds;
try
{
client.Send(message);
Console.Write(ex.Message.ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message.ToString());
}
For sharing purposes, I managed to resolve my problem by enabling access for less secure apps in Gmail.
It works like a charm now! https://www.google.com/settings/security/lesssecureapps
To authenticate SMTP in Outlook, the articles below are very useful too.
http://www.tradebooster.com/web-hosting-articles/how-to-enable-smtp-authentication-in-outlook-2010/
https://www.authsmtp.com/outlook-2010/default-port.html
//bulk Emails using mailkit you have to import it by nuget manager
//set in gmail https://myaccount.google.com/lesssecureapps?pli=1 to be on
// Read Text File
public void ReadFileAndSend()
{
using (StreamReader reader = new StreamReader(#"d:\Email.txt"))
{
while (!(reader.ReadLine() == null))
{
String line = reader.ReadLine();
if (line != "")
{
try
{
Send("", line.Trim());
Thread.Sleep(500);
}
catch
{
}
}
}
Console.ReadLine();
}
}
public void Send(String FromAddress,String ToAddress)
{
try
{
string FromAdressTitle = "";
string ToAdressTitle = "";
string Subject = "";
string BodyContent = "";
string SmtpServer = "smtp.gmail.com";
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
mimeMessage.Body = new TextPart("html")
{
Text = BodyContent
};
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
client.Authenticate("your email", "pass");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
client.Disconnect(true);
}
}
catch (Exception ex)
{
throw ex;
}
}
Answer Update 2023
After Google introduced a Two-step verification system in Google Accounts, it's not easy to use Gmail for your own personal usage so to solve this problem, I figured out a way to use Gmail as an email medium to send emails using C#.
The C# code for email service is included here: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Following just the 2-step tutorial from the above link, you can fix your issue in no time.

insert a link in to a email send using c#

I develop a program to send emails automatically using c#, and I want to insert a link to a web site to that email. How can I do it?
public bool genarateEmail(String from, String to, String cc, String displayName,
String password, String subjet, String body)
{
bool EmailIsSent = false;
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress(from, displayName);
m.To.Add(new MailAddress(to, displayName));
m.CC.Add(new MailAddress("xxx#gmail.com", "Display name CC"));
m.Subject = subjet;
m.IsBodyHtml = true;
m.Body = body;
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new
System.Net.NetworkCredential(from, password);
sc.EnableSsl = true;
sc.Send(m);
EmailIsSent = true;
}
catch (Exception ex)
{
EmailIsSent = false;
}
return EmailIsSent;
}
I want to send a link through this email. How should I add it to email?
You should be able to just add the mark-up for the link in your body variable:
body = "blah blah <a href='http://www.example.com'>blah</a>";
You shouldn't have to do anything special since you're specifying your body contains HTML (m.IsBodyHtml = true).
String body = "Your message : <a href='http://www.example.com'></a>"
m.Body = body;
Within the body. This will require that the body be constructed as HTML so the that a or can be used to render your link. You can use something like StringTemplate to generate the html including your link.
For some dynamic links, the email service providers will not show your link into email body if the link not prepend http (security issues)
like localhost:xxxx/myPage
m.body = "<a href='http://" + Request.Url.Authority + "/myPage'>click here</a>"

Send SMTP mail when an exception occurs

I'd be grateful if someone could tell me if I'm on the right track... Basically, I have a webservice i need to run for my app, I've put it into a try catch, if the try fails I want the catch to send me an email message with the details of the exception.
try
{
// run webservice here
}
catch (Exception ex)
{
string strTo = "scott#...";
string strFrom = "web#...";
string strSubject = "Webservice Not Run";
SmtpMail.SmtpServer = "thepostoffice";
SmtpMail.Send(strFrom, strTo, strSubject, ex.ToString());
}
Yes you are but you'd better wrapp yor exception handler in some kind of logger or use existing ones like Log4Net or NLog.
A quick and easy way to send emails whenever an Exception occurs can be done like this:
SmtpClient Server = new SmtpClient();
Server.Host = ""; //example: smtp.gmail.com
Server.Port = ; //example: 587 if you're using gmail
Server.EnableSsl = true; //If the smtp server requires it
//Server Credentials
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = "youremail#gmail.com";
credentials.Password = "your password here";
//assign the credential details to server
Server.Credentials = credentials;
//create sender's address
MailAddress sender = new MailAddress("Sender email address", "sender name");
//create receiver's address
MailAddress receiver = new MailAddress("receiver email address", "receiver name");
MailMessage message = new MailMessage(sender, receiver);
message.Subject = "Your Subject";
message.Body = ex.ToString();
//send the email
Server.Send(message);
Yes this the right way, if you don't want to use any logger tool.You can create function SendMail(string Exceptioin) to one of the your common class and than call this function from each catch block

Categories

Resources