In my application, I have a requirement where if a user clicks on invoice number the generated invoice statesment is attached to a composed email in outlook. Using code below i am able to send automated emails but i need to just compose and open the outlook window for user to review and edit the contents. Do not send. Kindly help.
public void pdfStatement(string InvoiceNumber)
{
InvoiceNumber = InvoiceNumber.Trim();
string mailServer = "server";
string fileName = InvoiceNumber;
string filePath = Server.MapPath("~/Content/reports/");
string messageBody = "Its an automated test email, please ignore if you receive this.";
CreateMessageWithAttachment(mailServer, filePath, fileName, messageBody);
}
public void CreateMessageWithAttachment(string mailServer, string filePath, string fileName, string messageBody)
{
MailMessage message = new MailMessage (
"user#domain.com",
"user#domain.com",
"TestEmail",
messageBody);
filePath = filePath + fileName + ".pdf";
// Create the file attachment for this e-mail message.
Attachment attach = new Attachment(filePath);
attach.Name = fileName + ".pdf";
// Add the file attachment to this e-mail message.
message.Attachments.Add(attach);
//Send the message.
SmtpClient client = new SmtpClient(mailServer);
var AuthenticationDetails = new NetworkCredential("user", "password");
client.Credentials = AuthenticationDetails;
client.Send(message);
}
not sure if this will help but how about u just create a form in tha page and allow user to type/see what they be sending.
Sample here
Also Preview button can help
EDIT:
Then u need to use Microsoft.Office.Interop.Outlook namespace to create a mail item.
First sample here
From the sample, the MailItem class(oMsg) also has a Display() Method which should display the created email.
Second sample (ASP.NET version)
Related
The official Gmail API documentation is horrendous. Not getting any clue to integrate Gmail API using .NET framework in vs2017. I wanted to send the input data of the Web form to a user's email.
It would be a three step process -
Define an HTML template which which describes how your mail should be presented.
Write a small c# code to replace all place holders like your form fields , user name, etc.
private string createEmailBody(string userName, string title, string message)
{
string body = string.Empty;
//using streamreader for reading my htmltemplate
using(StreamReader reader = new StreamReader(Server.MapPath("~/HtmlTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName); //replacing the required things
body = body.Replace("{Title}", title);
body = body.Replace("{message}", message);
//// Instead of message add you own parameters.
return body;
}
When form is submitted, call step 2 code first. Then use it's output to set mail body.
Code would be something like -
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
/// This mail from can just be a display only mail I'd
string emailFrom = "no-reply#gmail.com";
string subject = "your subject";
string body = createEmailBody();
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
/// Add more to IDs if you want to send it to multiple people.
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// This is required to keep formatting of your html contemts
/// Add attachments if you want, this is optional
mail.Attachments.Add(new Attachment(yourfilepath));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(your-smtp-account-email, your-smtp-account-password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Refer this link for working example
https://www.c-sharpcorner.com/UploadFile/33b051/sending-mail-with-html-template/
EDIT: For using GMail API
Using GMAIL APIs you will need two nuget packages:
1. Install-Package Google.Apis.Gmail.v1
2. Install-Package AE.Net.Mail
Code is very similar to what we have for normal SMTP mail send. It is explained at: http://jason.pettys.name/2014/10/27/sending-email-with-the-gmail-api-in-net-c/
In my view, users can search for a document and once they get the result, they can click on its id and they can download the document from specific url based on id: http://test.com/a.ashx?format=pdf&id={0}
For example, if the id is 10, then url to download document will be: http://test.com/a.ashx?format=pdf&id=10, and when user click on it they are able to download the document.
This is how it looks like in my view:
foreach (var item in Model)
{
<td>
<a href=#string.Format("http://test.com/a.ashx?format=pdf&id={0}",item.id)>
#Html.DisplayFor(modelItem => item.id)
</a>
</td>
}
And below is my controller action for SendEmail.
I am able to send email to the user. But i am having problem with sending attachments.
My question is: how can i attach the document that comes with the url to the email?
public static bool SendEmail(string SentTo, string Text, string cc)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("test#test.com");
msg.To.Add(SentTo);
msg.CC.Add(cc);
msg.Subject = "test";
msg.Body = Text;
msg.IsBodyHtml = true;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(???);
msg.Attachments.Add(attachment);
SmtpClient client = new SmtpClient("mysmtp.test.com", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
client.Credentials = new NetworkCredential("test", "test");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception)
{
return false;
}
return true;
}
If the PDF file is generated on an external site, you will need to download it in some way, for this you can use WebClient:
var client = new WebClient();
// Download the PDF file from external site (pdfUrl)
// to your local file system (pdfLocalFileName)
client.DownloadFile(pdfUrl, pdfLocalFileName);
Then you can use it on Attachment:
attachment = new Attachment(pdfLocalFileName, MediaTypeNames.Application.Pdf);
msg.Attachments.Add(attachment)
Consider using Postal It's open source libriary for ASP.Net MVC allowing you to send emails very easy. For example to attach file you can use such code:
dynamic email = new Email("Example");
email.Attach(new Attachment("c:\\attachment.txt"));
email.Send();
Also you may want to use HangFire to send email in background, please take a look at the Sending Mail in Background with ASP.NET MVC
Update: In order to get the PDF file path you can use Server.MapPath method to convert virtual path to the corresponding physical directory on the server.
I have a c# console application that I use to search a Gmail account for emails with attachments and download them. I am using MailKit.Net.Imap.ImapClient to do this.
If the email has been sent with the "Content-Disposition; attachment" set then all works well. If the email has been sent with "Content-Disposition; inline" set, the ImapClient does not see the attachments and I can't download them.
Below is the code I use to do this. Does anyone have any idea how to fix this?
static public void mail_ReadEmail()
{
string mail_login = "your login here";
string mail_password = "your password here";
string mail_folderName = "your gmail folder name here";
// Get client & open folder
ImapClient client = mail_GetImapClient(mail_login, mail_password);
IMailFolder folder = mail_GetIMailFolder(client, mail_folderName);
// Get emails
DateTime startTime = DateTime.Now.AddMonths(-6);
IList<UniqueId> email = folder.Search(SearchQuery
.DeliveredAfter(startTime)
.And(SearchQuery
.FromContains("canon.co.nz")));
// Loop through emails (oldest first)
for (int i = email.Count - 1; i >= 0; i--)
{
// Get message and display subject and date
MimeMessage message = folder.GetMessage(email[i]);
Console.WriteLine(message.Subject + " - " + message.Date.DateTime.ToShortDateString());
// Show all attachments for this message
foreach (MimePart part in message.Attachments)
Console.WriteLine("\t* " + part.FileName);
}
}
You can use the BodyParts property instead of the Attachments property.
For example, you could do this:
foreach (MimePart part in message.BodyParts.OfType<MimePart> ().Where (x => x.IsAttachment || (/* other criteria that suggests an attachment */))
Console.WriteLine("\t* " + part.FileName);
If you want to treat all MimeParts with a Content-Disposition filename attribute or a Content-Type name attribute set, then you could do:
!string.IsNullOrEmpty (x.FileName)
I have a program for sending my resume to emails of people who posted jobs if they included their email in their post.
so I send an email with their quote of the job description, date of when it was generated etc,
so each email is unique, But each email uploads the same file (resume.pdf) as Attachment.
right now each time I send an email I need to upload the same file (resume.pdf) // my resume
so this are my questions:
can I send each email and only upload my pdf resume once?
right now I use a smtp client library like this:
GMailSmtp gmail = new GMailSmtp(new NetworkCredential("username", "password"));
so each time I send an email I create a thread that opens a new connection which seems time consuming to me.
I was wondering if there is an API or library to create 1 connection and then send all the emails I want thru a queue or create a new thread just for sending the email.
Yes. If you're using a third-party server like Gmail, you will need to upload your resume with each email. BUT, there are lots of easy ways to do this in the background.
Play with this for a while and if you have specific questions or problems, post your code and your specific issue:
List<string> recipients = new List<string>();
BackgroundWorker emailer = new BackgroundWorker();
public void startSending()
{
emailer.DoWork += sendEmails;
emailer.RunWorkerAsync();
}
private void sendEmails(object sender, DoWorkEventArgs e)
{
string attachmentPath = #"path to your PDF";
string subject = "Give me a JOB!";
string bodyHTML = "html or plain text = up to you";
foreach (string recipient in recipients)
{
sendEmail(recipient, subject,bodyHTML,attachmentPath);
}
}
private void sendEmail(string recipientAddress, string subject, string bodyHTML,string pathToAttachmentFile)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add(recipientAddress);
mail.Subject = subject;
mail.Body = bodyHTML;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(pathToAttachmentFile);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Note that BackgroundWorker requires a reference to System.ComponentModel.
You could use separate thread for sending e-mails. For example you can do it as Shannon Holsinger suggested. You could also upload your resume to Dropbox or anywhere else and send the link instead of attaching a file.
In my view, users can search for a document and once they get the result, they can click on its id and they can download the document from specific url based on id: http://test.com/a.ashx?format=pdf&id={0}
For example, if the id is 10, then url to download document will be: http://test.com/a.ashx?format=pdf&id=10, and when user click on it they are able to download the document.
This is how it looks like in my view:
foreach (var item in Model)
{
<td>
<a href=#string.Format("http://test.com/a.ashx?format=pdf&id={0}",item.id)>
#Html.DisplayFor(modelItem => item.id)
</a>
</td>
}
And below is my controller action for SendEmail.
I am able to send email to the user. But i am having problem with sending attachments.
My question is: how can i attach the document that comes with the url to the email?
public static bool SendEmail(string SentTo, string Text, string cc)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("test#test.com");
msg.To.Add(SentTo);
msg.CC.Add(cc);
msg.Subject = "test";
msg.Body = Text;
msg.IsBodyHtml = true;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(???);
msg.Attachments.Add(attachment);
SmtpClient client = new SmtpClient("mysmtp.test.com", 25);
client.UseDefaultCredentials = false;
client.EnableSsl = false;
client.Credentials = new NetworkCredential("test", "test");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.EnableSsl = true;
try
{
client.Send(msg);
}
catch (Exception)
{
return false;
}
return true;
}
If the PDF file is generated on an external site, you will need to download it in some way, for this you can use WebClient:
var client = new WebClient();
// Download the PDF file from external site (pdfUrl)
// to your local file system (pdfLocalFileName)
client.DownloadFile(pdfUrl, pdfLocalFileName);
Then you can use it on Attachment:
attachment = new Attachment(pdfLocalFileName, MediaTypeNames.Application.Pdf);
msg.Attachments.Add(attachment)
Consider using Postal It's open source libriary for ASP.Net MVC allowing you to send emails very easy. For example to attach file you can use such code:
dynamic email = new Email("Example");
email.Attach(new Attachment("c:\\attachment.txt"));
email.Send();
Also you may want to use HangFire to send email in background, please take a look at the Sending Mail in Background with ASP.NET MVC
Update: In order to get the PDF file path you can use Server.MapPath method to convert virtual path to the corresponding physical directory on the server.