Adding attachments using url in mail with C sharp - c#

I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,

I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}

It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}

Related

Send e-mail with image on body

I want to send an e-mail with a logo at the top of the body. This is my method:
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}
The method is sending the e-mail, but the image is being sent as an attachment. I've tried to do this:
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"), MediaTypeNames.Image.Jpeg);
But when I add "MediaTypeNames.Image.Jpeg" in this line, the e-mail is sent without the image at all.
Someone can help me on this? Thanks in advance!
You could convert your image to base64 and add that in src or you could just give the page where is the image is located.
You could try the library MailKit. Sending embedded images works well with this library.
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
stream.Position = 0;
var resource = builder.LinkedResources.Add(contentId, stream);
resource.ContentId = contentId;
// in the email message, there is img with src="cid:contentId"
Another example of embedding images is here.
You can use it :
public bool SendEmail(string toAddress)
{
SmtpClient smtpServer = new SmtpClient("the server");
try
{
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<image src=cid:logo style=\"height: 50px;\"><br>Hello World", null, MediaTypeNames.Text.Html);
LinkedResource imageResource = new LinkedResource(Server.MapPath(#"..\..\images\logo.png"));
imageResource.ContentId = "logo";
htmlView.LinkedResources.Add(imageResource);
smtpServer.Port = 0; //add port here
smtpServer.Credentials = new NetworkCredential("user", "pass");
smtpServer.EnableSsl = false;
MailMessage message = new MailMessage();
message.To.Add(toAddress);
message.From = new MailAddress("the address");
message.Subject = "Some subject";
//add file here
Attachment attachment = new Attachment("c://image");
attachment.ContentDisposition.Inline = true;
message.Attachments.Add(attachment);
message.AlternateViews.Add(htmlView);
message.IsBodyHtml = true;
smtpServer.Send(message);
smtpServer.Dispose();
return true;
}
catch (Exception ex)
{
return false;
}
}

SMTP server not getting credentials from C# code

I'm trying to set up an automatic email sender.
My smtp server requires authentication. I'm not using ssl but still I'm getting the following response from server:
The server response was: 5.7.1 You are not authorized, authentication is required.
And if I check on the server it got an empty username.
Here is my code:
public void email_send(string mailadress,string docname)
{
string host = "myhost";
string username = "user";
string password = "password";
int port = 625;
var nc = new NetworkCredential(username, password);
var auth = nc.GetCredential(host,port,"Basic");
using (var mail = new MailMessage())
using (var SmtpServer = new SmtpClient())
{
SmtpServer.Host = host;
SmtpServer.Port = port;
SmtpServer.Credentials = auth;
mail.From = new MailAddress("fromadress");
mail.To.Add(mailadress);
mail.Subject = "Subject";
mail.Body = "Body";
Attachment attachment;
attachment = new Attachment("D:/" + docname + ".pdf");
mail.Attachments.Add(attachment);
mail.IsBodyHtml = true;
SmtpServer.DeliveryFormat = SmtpDeliveryFormat.International;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Send(mail);
}
}

Links not getting created while sending email through asp.net mvc

Hi i am sending download brochure link in the email but i am receiving only text instead of link in the mail
below is the code from which i am sending the mail
StringBuilder sb = new StringBuilder();
sb.Append("<html><body><a href='"+Server.MapPath("~/Documents/Brochure.pdf") +"'>Download Brochure </a>");
sb.Append("<br></body></html>");
string messageBody = sb.ToString();
string AdminEmail = ConfigurationManager.AppSettings["AdminEmailForEmail"];
string AdminPassword = ConfigurationManager.AppSettings["AdminPasswordForPassword"];
string Reciepient = Email;
string subject = "Brochure Download";
string FromMail = "info#testmail.in";
string emailTo = Reciepient;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("testmail.in");
mail.From = new MailAddress(FromMail);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = messageBody;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential(AdminEmail, AdminPassword);
SmtpServer.EnableSsl = false;
try
{
SmtpServer.Send(mail);
return true;
}
catch (Exception ex)
{
return false;
}

i can't send mail from smtp.gmail.com SMTP CLIENT from asp.net with c#

This is my mail sending code.....
string fromAddress = "from#abc.gov.in";
string toAddress = "darpansamani#gmail.com";
string fromPassword = "*********";
string subject = "Citizens Forum";
string body = "Demo Body";
MailMessage mail = null;
using (mail = new MailMessage(new MailAddress(fromAddress), new MailAddress(toAddress)))
{
mail.Subject = subject;
mail.Body = body;
mail.To.Add(toAddress);
SmtpClient smtpMail = null;
using (smtpMail = new SmtpClient("smtp.gmail.com"))
{
smtpMail.Port = 587;
smtpMail.EnableSsl = false;
smtpMail.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtpMail.UseDefaultCredentials = false;
smtpMail.Send(mail);
Console.WriteLine("sent");
Console.ReadLine();
}
}
This code give me error of "Unable to read data from the transport connection: net_io_connectionclosed."
i am using asp.net with c# website and cant send mail to my mail address please help me
Thank you

Send Email without attachments

I have a Problem i know how to send email with attachment but i want to learn that if i dont have screenshot.png then i want to send it without attachment my code is below
string email = "hammadptc93#gmail.com";
string pass = "mypassword";
NetworkCredential loginInfo = new NetworkCredential(email, pass);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("hammadptc93#gmail.com"));
msg.Body = value;
msg.Subject = Environment.UserName +" " +
Environment.UserDomainName +" "+ Environment.SystemDirectory ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.SendAsync(msg, "hammad");
Simply checking whether file is present or not will be enough.
if(File.Exists("screenshot.png"))
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
}
Use File.Exists method to check whether you have the attachment. If File.Exists returns false, side step from following lines (wrap them in a if statement)
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
Hope this helps

Categories