How to send automated emails? - c#

I am working in C# and Sql server. I have a table Email that contains fields from, to, subject, body, CC, BCC etc. When something happens in it saves the notification. I want to send the mail notification that newly inserted in Email table automatically. Is there is a way in SQL Server??? Which send emails automatically and deletes the record from the table. OR what is the efficient way for this task (from C#code or else).
Thanks,
Girish

What I would do is set up your sql server to have sql Mail and then use a trigger against your table to fire the mail event and then delete the row.
Here's how to configure your sever for sql mail
SQL Mail Config

You are talking about two problems -
1. Send email from c#
2. Delete from table
For #1, refer here http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/a75533eb-131b-4ff3-a3b2-b6df87c25cc8

try
{
var fromAddress = new MailAddress("address#gmail.com", "Support");
var toAddress = new MailAddress(user.email, user.username);
const string subject = "Processing";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("username", "password")
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = dataToSend
})
{
message.IsBodyHtml = true;
smtp.Send(message);
}
}
catch (Exception)
{
Model.Message = "Exception Occured During Mail Sending";
}

Related

How do I call a method to automatically send an email in the controller?

I need to be able to send automatic emails to any users who have registered new accounts, changed passwords, and/or created new orders.
I've been given the SendEmail file, which belongs in the "Utilities" folder in my solution.
using System;
using System.Net.Mail;
using System.Net;
namespace SendEmail
{
public static class EmailMessaging
{
public static void SendEmail(String toEmailAddress, String emailSubject, String emailBody)
{
//Create a variable for YOUR TEAM'S Email address
//This is the address that will be SENDING the emails (the FROM address)
String strFromEmailAddress = "email#gmail.com";
//This is the password for YOUR TEAM'S "fake" Gmail account
String strPassword = "Password";
//This is the name of the business from which you are sending
//TODO: Change this to the name of the company you are creating the website for
String strCompanyName = "Team Final Project";
//Create an email client to send the emails
//port 587 is required to work, do not change it
var client = new SmtpClient("smtp.gmail.com", 587)
{
UseDefaultCredentials = false,
//This is the SENDING email address and password
//This will be your team's email address and password
Credentials = new NetworkCredential(strFromEmailAddress, strPassword),
EnableSsl = true
};
//Add anything that you need to the body of the message
//emailBody is passed into the method as a parameter
// /n is a new line – this will add some white space after the main body of the message
//TODO: Change or remove the disclaimer below
String finalMessage = emailBody + "\n\n Thank you, come back again soon!";
//Create an email address object for the sender address
MailAddress senderEmail = new MailAddress(strFromEmailAddress, strCompanyName);
//Create a new mail message
MailMessage mm = new MailMessage();
//Set the subject line of the message (including your team number)
mm.Subject = "Team ## - " + "Thank you!";
//Set the sender address
mm.Sender = senderEmail;
//Set the from address
mm.From = senderEmail;
//Add the recipient (passed in as a parameter) to the list of people receiving the email
mm.To.Add(new MailAddress(toEmailAddress));
//Add the message (passed)
mm.Body = finalMessage;
//send the message!
client.Send(mm);
}
}
}
My problem is that neither I nor my team members know how to implement call this from the controller in a way that will be sent automatically and with the user's email and name. We imagine they will be in the Account and Orders controllers. The accounts controller has the register and change password methods, which work, and the orders controller has the complete order method.
Also, we are not using a confirmation view, it has to be an automatic email.
We need some direction in figuring out where exactly we need to call the method from and how.
The most helpful thing I've found on the internet today is this block of code for a test message that is not intended to be sending automatic emails.
public static void CreateTestMessage(string server)
{
MailAddress from = new MailAddress("sender#gmail.com", "Team Project");
MailAddress to = new MailAddress("reciever#gmail.com", "Customer");
MailMessage message = new MailMessage(from, to);
message.Subject = "Password Changed";
message.Body = #"This is a confirmation email that your password has been changed.";
SmtpClient client = new SmtpClient(server);
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
ex.ToString());
}
}
Everything is being coded on MS VS
First create a service for EmailService and put SendEmailAsync Method in it
and call this method on your Controller.
In Method body:
1-Create your message:
var mm = new MailMessage()
2-Then you should build your smtp:
using var smtpClient = new SmtpClient();
3-Then connect it to your server
await smtpClient.ConnectAsync(
"your host",
"port",
SecureSocketOptions.SslOnConnect);
4-Now send your Email:
await smtpClient.SendAsync(mm);
5-Make sure that disconnect from your client:
await smtpClient.DisconnectAsync(true);
Note: It may give you an Exception while Connecting or Sending your Email so don't forget try catch block.
6-For Automation you can use a EmailAccount Table with relation with your Customer Table and keep your message data in it.
for ex: body ,subject..... .
In your Contorller you have your Customer So you can get his EmailAccount from DataBase and pass EmailAccount Entity to SendEmailAsync Method.
instead of creating message in body, get it from EmailAccount Entity and then countinue the Steps.
7-Enjoy it :)

How to send email using ASP.NET, C# and GMail

I have attempted to send an email using the GMail SMTP, and followed the guides on various other questions but I still cannot get emails to send from my GMail account.
This is the code I'm using:
protected void emailSend_Click(object sender, EventArgs e)
{
var fromAddress = new MailAddress(inputEmail.Text, inputName.Text);
var toAddress = new MailAddress("spikey666#live.co.uk", "Liane Stevenson");
const string fromPassword = "*********";
const string subject = "Web Dev Wolf Message";
var body = inputMessage.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("webdevelopwolf#gmail.com", fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
These are the things I've checked so far:
Turning on less secure apps on GMail
Checked the Gmail Username and Password are correct
Debugged and checked that all text fields have values and are loaded into variables
Check other port numbers suggested by Gmail help
Turned on POP/IMAP functionality on Gmail
Is there anything else I could be missing?
Before calling SmtpClient.Send(), add:
smtp.UseDefaultCredentials = false;
According to the MSDN SmtpClient page, UseDefaultCredentials is set to false by default, but there seems to be a bug somewhere that is setting it to true. Explicitly set it to false before sending the message and it should be all set.

sending email failed in .net when using google smtp server

I am trying to send email like this
var fromAddress = new MailAddress("fromaddress", "From Name");
var toAddress = new MailAddress("toaddress", "To Name");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Console.WriteLine("Sent");
Console.ReadLine();
but it gives this error .
The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.5.1 Authentication Required.
I am sing this code in simple console application on my local host . So whats the issue in my code ?
Update
I changed fromAddress email and it send email successfully . But i don't receive any email in my toAddress email's inbox/Spam .
Try to add DeliveryMethod = SmtpDeliveryMethod.Network when creating SmtpClient.
See post:
https://stackoverflow.com/a/489594/1432770
There is a variety of reasons for this discussed here:
Sending email through Gmail SMTP server with C#
Your code in the first link has worked for me.
Do you use two steps verification?
You need to sign in using application-specific passwords: https://support.google.com/accounts/answer/185833?hl=en
Your code worked for me too!

How to send email [duplicate]

This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)

Problem with app sending email followed by two empty emails

My app is sending 3 emails at the same time to the recipient, one being the correct email, and the other two contain the subject line, but an empty message. Could this code some how cause that? If not what do you suggest?
var fromAddress = new MailAddress(domainAddress, displayName);
var toAddress = new MailAddress(oInfo.SiteUser.email, oInfo.customerName);
var Bcc = new MailAddress("deleted");
var smtp = new SmtpClient
{
Host = SmtpHost(),
Port = SmtpPort(),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(SmtpUsername(), SmtpPassword())
};
using (var msg = new MailMessage(fromAddress, toAddress)
{
IsBodyHtml = true,
Subject = "Confirmation for your recent order at " + displayName,
Body = body
})
{
msg.Bcc.Add(Bcc);
smtp.Send(msg);
}
No, that code won't send more than one mail.
Either you have some more code that is sending mail, or you are executing that code three times, but with different values for body.
The only problem I can see with that code is the line
var Bcc = new MailAddress("deleted");
but I assume you modified it for posting here?
I can't see an issue that would cause what you're seeing. I'd check the headers in the emails for clues. Also capturing network traffic on the machine sending the emails could help.

Categories