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.
Related
I am working on a uwp app to send html email with embedded image. I was using EASendMail nuget pakage and it was fine after some time my app shows error:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond. (Exception from
HRESULT: 0x8007274c)
I think the trial period has expired what should I do?
using EASendMailRT;
https://www.emailarchitect.net/easendmail/kb/csharp.aspx?cat=8
I can't find any alternative
try
{
string ToAddress = MailSendPage.toAddressTxtBox;
string Subject = MailSendPage.subjectTxtBox;
SmtpMail oMail = new SmtpMail("TryIt");
oMail.From = new MailAddress(username);
if(!String.IsNullOrEmpty(ToAddress)&& !String.IsNullOrEmpty(Subject))
{
oMail.To.Add(new MailAddress(ToAddress));
oMail.Subject = Subject;
EASendMailRT.SmtpClient oSmtp = new EASendMailRT.SmtpClient();
SmtpServer oServer = new SmtpServer(host);
oServer.User = username;
oServer.Password = password;
oServer.Port = port;
if (IsStackPanalHasImg() == true)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
string[] files = Directory.GetFiles(localFolder.Path + #"\ProjectImages");
foreach (string eachfile in files)
{
foreach (string name in covertToHtml.ControlName)
{
string pattern = string.Format("{0}.jpeg", name);
if (Regex.IsMatch(eachfile, pattern))
{
Attachment oAttachment = await oMail.AddAttachmentAsync(eachfile);
oAttachment.ContentID = name;
}
}
}
}
await oSmtp.SendMailAsync(oServer, oMail);
popUpMsgs.popup(" The Mail has been sent");
}
}
catch (Exception ep)
{
popUpMsgs.popup(String.Format("Failed to send email with the following error: {0}", ep.Message));
}
The built-in e-mail API only support sending plain text e-mail messages as Docs state:
This method only sends plain text messages. You can't set the body of the message to the HTML format.
What you can do is attach images to the e-mail:
EmailMessage mail = new EmailMessage();
mail.Sender = new EmailRecipient("test#example.com");
mail.To.Add(new EmailRecipient("someone#example.com"));
mail.Subject = "Hello";
mail.Body = "World";
var file = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/StoreLogo.png"));
mail.Attachments.Add(new EmailAttachment(file.Name, file));
await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(mail);
In addition, sending attachments works well only in case of the built-in UWP Outlook Mail client. Classic Outlook will most likely ignore the attachments altogether.
If you need to embed the image, you will need to use a e-mail service. I can recommend SendGrid or MailGun. Both have C# APIs which work like a breeze. They are also free for limited number of e-mails.
There are several ways you can embed the images in a HTML e-mail message.
The oldest is using CID (Content ID) which you were using in your question.
Second option is using Base64 encoding. You first turn your image into a Base64 string. There are many tutorials on this, for example in this blogpost. Then you can just embed the image in the src of your <img> tag:
<img src="data:image/jpeg;base64, YOURIMAGEINBASE64"/>
Finally you can embed an image which is hosted somewhere. This scales the best if you need to send the e-mail to many recipients, but of course requires actually hosting the image somewhere. Of the three methods it is also supported in most clients.
All three approaches are described in detail in this post.
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 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.
I know that thats not a new question but i want to know that when i set image in my Email Body using the below C# code, why my image not show on mail
SmtpClient client = new SmtpClient();
MailMessage myMessage = new MailMessage();
String Body = "<img src=\"images/logo2.png\" style=\"width:75px; height:75px;\" />";
myMessage.To.Add(new MailAddress(txtemail.Text));
myMessage.Subject = "Subject";
myMessage.Body = Body;
myMessage.IsBodyHtml = true;
try
{
client.Send(myMessage);
}
catch (Exception ex)
{
Response.Write("Unable to send Email" + ex);
}
I am using asp.net c#.
Email will be opened in an email client and doesn't know which web-application to access the image. So your image src shouldn't be relative to the application. Change the src to include the full url:
<img src=\"http://www.somedomain.nl/images/logo2.png\"
Test the url in a browser by taking the src value and try browsing it. If it doesn't work, the src value isn't retrievable.