System.Net.Mail.Attachment file url contains a # [duplicate] - 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.

Related

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 .

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/

c# Sending emails in threads using 1 connection

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.

set image in email body using html c#

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.

Send email with attachment from a specific url in 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.

How to send email in richtext format to Outlook?

It works great to send emails (to Outlook) in HTML format by assigning the text/html content type string like so:
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("--#---.com");
message.ReplyTo = new MailAddress("--#---.com");
message.To.Add(new MailAddress("---#---.com"));
message.Subject = "This subject";
message.Body = "This content is in plain text";
message.IsBodyHtml = false;
string bodyHtml = "<p>This is the HTML <strong>content</strong>.</p>";
using (AlternateView altView = AlternateView.CreateAlternateViewFromString(bodyHtml,
new ContentType(MediaTypeNames.Text.Html)))
{
message.AlternateViews.Add(altView);
SmtpClient smtp = new SmtpClient(smtpAddress);
smtp.Send(message);
}
}
The email is correctly recognized as HTML in Outlook (2003).
But if I try rich text:
MediaTypeNames.RichText;
Outlook doesn't detect this, it falls back to plain text.
How do I send email in rich text format?
The bottom line is, you can't do this easily using System.Net.Mail.
The rich text in Outlook is sent as a winmail.dat file in the SMTP world (outside of Exchange).
The winmail.dat file is a TNEF message. So, you would need to create your richtext inside of the winmail.dat file (formatted to TNEF rules).
However, that's not all. Outlook uses a special version of compressed RTF, so, you would also need to compress your RTF down, before it's added to the winmail.dat file.
The bottom line, is this is difficult to do, and unless the client really, really needs this functionality, I would rethink it.
This isn't something you can do with a few lines of code in .NET.
You can also achieve this by adding another alternate view before your calendar view as below:
var body = AlternateView.CreateAlternateViewFromString(bodyHtml, new System.Net.Mime.ContentType("text/html"));
mailMessage.AlternateViews.Add(body);
This worked for me..
public void sendUsersMail(string recipientMailId, string ccMailList, string body, string subject)
{
try
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("norepl#xyz.com", "Tracker Tool");
Msg.To.Add(recipientMailId);
if (ccMailList != "")
Msg.CC.Add(ccMailList);
Msg.Subject = subject;
var AltBody = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
Msg.AlternateViews.Add(AltBody);
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("mail.xyz.com");
smtp.Send(Msg);
smtp.Dispose();
}
catch (Exception ex)
{
}
}

Categories

Resources