sending email based on a gridview column containing email addresses - c#

May I know how to send email based on gridview column containing email addresses?
I am currently using asp.net and c#. I'm also currently using smtp gmail for the email.
Currently, I had a gridview1 which contain customers (email, name, accountNo) that had bounced cheque, however I wish to send an standard email, to all these customers upon clicking a button. May I know how should i go about it? Their email is stored in database and will be shown on gridview.
private void SendEMail(MailMessage mail)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("#gmail.com", "password");
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}

The easiest would be loop through the dataset that you have bound to grid view. But since you have asked about gridview, here is how you can loop through gridview rows
On button_click write this
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//considering 1st column contains email address
//if not, replace it with correct index
email = item.Cells[0].Text;
//code to send email
}
UPDATE 2
Updating my code to use your sendEmail function
public void button_click(object sender, EventArgs e)
{
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//if not, replace it with correct index
email = item.Cells[4].Text;
//code to send email
//reciever email add
MailAddress to = new MailAddress(email);
//sender email address
MailAddress from = new MailAddress("your#email");
MailMessage msg = new MailMessage();
//use reason shown in grid
msg.Subject = item.Cells[3].Text;
//you can similar extract FName, LName, Account number from grid
// and use it in your message body
//Keep your message body like
str email_msg = "Dear {0} {1}, Your cheque for account number {2} bounced because of the reason {3}";
msg = String.Format(email_msg , item.Cells[0].Text,item.Cells[1].Text,item.Cells[2].Text,item.Cells[3].Text);
msg.Body = email_msg ;
msg.From = from;
msg.To.Add(to);
SendEMail(msg);
}
}

try to save the e-mail addresses in an array.
then do a foreach and send the e-mail that are in the array!
example:
CLASS:
public SmtpClient client = new SmtpClient();
public MailMessage msg = new MailMessage();
public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password");
public void Send(string sendTo, string sendFrom, string subject, string body)
{
try
{
//setup SMTP Host Here
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
//convert string to MailAdress
MailAddress to = new MailAddress(sendTo);
MailAddress from = new MailAddress(sendFrom);
//set up message settings
msg.Subject = subject;
msg.Body = body;
msg.From = from;
msg.To.Add(to);
// Send E-mail
client.Send(msg);
}
catch (Exception error)
{
}
}
SENDING E-MAILS: (button_click)
//read the emails from the database and save them in an array.
//count how many are the emails, ex: int countEmails = SqlClass.Function("select emails from table").Rows.Count;
string[] emails = new string[countEmails];
foreach (string item in emails)
{
//send e-mail
callClass.Send(item, emailFrom, subject, body); //you can adapt the class
}

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

sending mail failure in asp.net using c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
This mail code is working in localhost i.e on my computer but when i uopload it on server it is not working.
The error is : Failure sending mail. please tell me where is the problem.
if (Session["userinfo"] != null)
{
lblTest.Text = Session["userinfo"].ToString();
MailMessage msg = new MailMessage();
msg.From = new MailAddress("shop.bcharya#gmail.com");
msg.To.Add(new MailAddress("bcc#dr.com"));
msg.To.Add(new MailAddress("info#yzentech.com"));
msg.Subject = "Mail from BcharyaCorporation.online shopping site";
msg.Body = ""+lblTest.Text+" wants to buy some products. please contact with him/her";
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.gmail.com";
// sc.Port = 25;
sc.Credentials = new NetworkCredential("shop.bcharya#gmail.com", "mypassword");
sc.EnableSsl = true;
try
{
sc.Send(msg);
lblPayment.Text = "Sorry. Currently we are out of online payment service. We will contact you for payment process. Thank you for buying this product.";
}
catch (Exception ex)
{
lblPayment.Text=ex.Message.ToString();
Response.Write(ex.Message);
}
}
For gmail mail settings add Port number too
sc.Port = 587;
after this line
sc.Host = "smtp.gmail.com";
Only use port 587 and SSL if the SMTP server supports that (GMail and Hotmail for example). Some servers just use port 25 and no SSL.
Use below method and then check :
SmtpClient sc = new SmtpClient(string); //sends e-mail by using the specified SMTP server
You can use this below given code for sending email. Here sending the error details through email is one method. Try this code for sending email.
using System.Web.Mail
public static bool SendErrorEmail(string to, string cc, string bcc, string subject, string body, MailPriority priority, bool isHtml)
{
try
{
using (SmtpClient smtpClient = new SmtpClient())
{
using (MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress(“yourmail#domain.com”, “Your name”);
// You can specify the host name or ipaddress of your server
smtpClient.Host = “mail.yourdomain.com”; //you can specify mail server IP address here
//Default port is 25
smtpClient.Port = 25;
NetworkCredential info = new NetworkCredential(“yourmail#domain.com”, “your password”);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = info;
//From address will be given as a MailAddress Object
message.From = from;
message.Priority = priority;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = subject;
// CC and BCC optional
if (cc.Length > 0)
{
message.CC.Add(cc);
}
if (bcc.Length > 0)
{
message.Bcc.Add(bcc);
}
//Body can be Html or text format;Specify true if it is html message
message.IsBodyHtml = isHtml;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
}
return true;
}
catch (Exception ee)
{
Logger.LogError(ee, “Error while sending email to ” + toAddress);
throw;
}
}

failed to send email from yahoo server in gmail is working

for sending email i set server name smtp.mail.yahoo.com and port is 465 i trying to send email but failed to send email
what is the correct servername and smtp port to send email using yahoo
what other configuration i needed to set ?
my code is here :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(address);
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress(from);
message.Body = body;
message.Bcc.Add(bcc);
message.CC.Add(cc);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.mail.yahoo.com");
smtp.Credentials = new System.Net.NetworkCredential(emailid,password);
smtp.Port = 465;
smtp.EnableSsl = true;
smtp.Send(message);
I just tried the code and I think the yahoo mail server does not use SSL, because if you comment out
//smtp.Port = 465;
//smtp.EnableSsl = true;
it works.
I am not confirm about your smtp server settings these are working fine for me..
replace your smtp server settings and have idea from this code snippet.
some of the smtp server standart settings are here:
http://www.emailaddressmanager.com/tips/mail-settings.html
//Send mail using Yahoo id
protected void Button2_Click(object sender, EventArgs e)
{
String frmyahoo = "fromid#yahoo.com"; //Replace your yahoo mail id
String frmpwd = "fromidpwd"; //Replace your yahoo mail pwd
String toId = txtTo.Text;
String ccId = txtCc.Text;
String bccId = txtBcc.Text;
String msgsubject = txtSubject.Text;
String mailContent = txtContent.Text;
try
{
MailMessage msg = new MailMessage();
msg.To.Add(toId);
MailAddress frmAdd = new MailAddress(frmyahoo);
msg.From = frmAdd;
//Check user enter CC address or not
if (ccId != "")
{
msg.CC.Add(ccId);
}
//Check user enter BCC address or not
if (bccId != "")
{
msg.Bcc.Add(bccId);
}
msg.Subject = msgsubject;
//Check for attachment is there
if (FileUpload1.HasFile)
{
msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
msg.IsBodyHtml = true;
msg.Body = mailContent;
SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = false;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
clear();
Label1.Text = "Mail Sent Successfully";
}
catch (Exception ex)
{
Label1.Text = "Unable to send Mail Please try again later";
}
}

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}

Categories

Resources