Email From ASP.net is going as HTML attachment - c#

As the title says, I am sending email from my ASP.net web application without any attachment (for now) but strangely the body of email is going as a separate HTML file attached to blank email like when I click the HTML file it opens the body in separate window with everything that I have written in body as standalone HTML file, this is only happening when I send email to some portals like e-lance but when I send it to gmail or hotmail address then email is going perfectly with no attachment and body-text appearing where it should.
My email code is
public bool sendMail(string messageSubject, System.Net.Mail.MailAddress fromEmailAddress, System.Net.Mail.MailAddress toEmailAddress, string source_id, string messageText)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.IsBodyHtml = true;
mail.Subject = messageSubject;
mail.From = fromEmailAddress;
mail.To.Add(toEmailAddress);
mail.Body = messageText;
SmtpClient relayServer = new SmtpClient();
List<KeyValuePair<string, string>> commandParameters = new List<KeyValuePair<string,string>>();
commandParameters.Add(new KeyValuePair<string,string>("#source_id", source_id));
DataTable sourcesTable = SQLSelect("SELECT * FROM LogiCrmSources WHERE source_id = #source_id", commandParameters);
relayServer.Host = sourcesTable.Rows[0]["source_smtp"].ToString();
relayServer.Port = Convert.ToInt16(sourcesTable.Rows[0]["source_smtp_port"].ToString());
if (relayServer.Port == 25)
{
relayServer.EnableSsl = false;
}
else
{
relayServer.EnableSsl = true;
}
relayServer.Credentials = new System.Net.NetworkCredential(sourcesTable.Rows[0]["source_email"].ToString(), sourcesTable.Rows[0]["source_password"].ToString());
try
{
relayServer.Send(mail);
return true;
}
catch(SmtpFailedRecipientException exp)
{
return false;
}
}

Not all clients can handle html emails properly. Gmail for example can while the portals you mention can't. In those cases the body of the email as sent as an attachment.

Related

how to do attachments from a specific directory when sending an email

So I'm trying to add an attachment when I send an email, but I am not sure how. The email works perfectly fine, but it's the adding onto the attachment for the email which doesn't work. I'm not trying to use any specific platform and just sending it via through the console essentially. I tried msgObj.attachments1.add(...) but it didn't work with it.
using (SmtpClient client = new SmtpClient("10.10.101.10", 500))
{
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(username,password);// has username and password credentials doesnt contain actual username and pass
MailMessage msgObj = new MailMessage();
List<string> attachments1 = new List<string>();
attachments1.Add(#"C:\Users -test.xlsx");
msgObj.IsBodyHtml = true; //always sets true, if the body contains html it turns text to html
msgObj.To.Add(Destination);
msgObj.From = new MailAddress("test#mail.com"); //you can send emails on behalf of somebody
msgObj.Subject = YourMessageSubject;
// msgObj.Body = YourMessageBody; //need to edit the body remember to use the message body to call upon it
msgObj.Body = messageBody2; //html
client.Send(msgObj); // sends the message
}
}
catch (Exception)
{
Console.WriteLine("somethings broken");
}
Try attaching it:
msgObj.Attachments.Add(new Attachment(#"C:\Users -test.xlsx"));

C# How to set 'return-path' for smtp mail

I am trying to set the 'return-path' for my emails but I'm not seeing it as an available parameter. It seems like replytolist is not the same thing. I wan't to set the location that bounced emails are delivered. Here is my code so far:
private static void SendMail(string html,string taxId,string toEmail,string filePath,string fromEmail,string replyToEmail,string emailSubject,string emailAttachPath)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromEmail);
mail.To.Add(toEmail);
mail.Subject = emailSubject;
mail.Body = html;
//specify the priority of the mail message
mail.ReplyToList.Add(replyToEmail);
SmtpClient SmtpServer = new SmtpClient("smtp.server.com");
SmtpServer.Port = 25;
SmtpServer.UseDefaultCredentials = true;
SmtpServer.EnableSsl = false;
mail.IsBodyHtml = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
If you dont write return path emailaddress. Server will take from email address convert into the return path. You also can see email report in your email original source.
If you want to add custom reutn path you can use
MailMessage message = new MailMessage();
message.Headers.Add("Return-Path", "response#*****.biz");
Also if you using postfix and you want add return path Automatically You will have to make changes in two files
canonical :- put your return path emailaddress here.
//reply#domain.com
main.cf :- write your code in main.cf file
canonical_classes = envelope_sender
sender_canonical_maps = regexp:/etc/postfix/canonical

Why image is not displaying in html mail in gmail?

I'm trying to add an image in HTML mail. It is displaying when I save that body as html file, but when I send that html body as an email through GMail, the image is not displaying. Can anyone tell me the reason?
I set the source of the image in this way:
var image = body.GetElementsByTagName("img");
string imageAttachmentPath = Path.Combine(Globals.NotificationTemplatesPath, "Header.png");
foreach (XmlElement img in image)
{
img.SetAttribute("src", imageAttachmentPath);
break;
}
//thats the method in which i am sending email.
public static void SendMessageViaEmailService(string from,
string sendTo,
string carbonCopy,
string blindCarbonCopy,
string subject,
string body,
bool isBodyHtml,
string imageAttachmentPath,
Hashtable images,
List<string> attachment,
string title = null,
string embeddedImages = null)
{
Attachment image = new Attachment(imageAttachmentPath);
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true; // email body will allow html elements
msg.From = new MailAddress(from, "Admin"); // setting the Sender Email ID
msg.To.Add(sendTo); // adding the Recipient Email ID
if (!string.IsNullOrEmpty(carbonCopy)) // add CC email ids if supplied.
msg.CC.Add(carbonCopy);
msg.Subject = subject; //setting email subject and body
msg.Body = body;
msg.Attachments.Add(image);
//create a Smtp Mail which will automatically get the smtp server details
//from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "smtp.gmail.com";
SmtpMail.Port = 587;
SmtpMail.EnableSsl = true;
SmtpMail.UseDefaultCredentials = false;
SmtpMail.Credentials = new System.Net.NetworkCredential(from, "password");
// sending the message.
try
{
SmtpMail.Send(msg);
}
catch (Exception ex) { }
}
More than likely your image SRC attribute is not an absolute, publicly-accessible URI. Any file-system or local URI's will not show the image in the email.
Specifically, these will not work:
c://test.png
test.png
/folder/test.png
http://localhost/test.png
http://internaldomain/test.png
Ensure that your image urls are
absolute (i.e. start with the protocol like http://)
includes a full path to the image
the domain is a public domain
Try the code part from this thread:
// creating the attachment
System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(#"c:\\test.png");
inline.ContentDisposition.Inline = true;
// sending the message
MailMessage email = new MailMessage();
// set the information of the message (subject, body ecc...)
// send the message
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
smtp.Send(email);
email.Dispose();

Asp.Net Email Attachment Displaying Inline on Mobile (iPhone)

I have an .Net 4.5 application that sends an email, with an attachment. It works as expected when the email is opened on a desktop, but when opened on a mobile (iPhone in this case) the attachment shows as inline HTML not as an attachment.
When however I forward the same email from my desktop to the phone, the attachment shows up correctly on my phone so I am almost certain that it has to do with how I am specifying mime or content-type, disposition etc. but I can't see what I am doing wrong.
Here is the code - note that
att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
does create an attachment on iPhone but it is of type = mime-attachment that will not open.
I'm stumped & client awaits - any help greatly appreciated !
private void SendNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, "text/html");
//specifying this creates an attachment of type "mime-attachment" that does not open
//att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}
Solved after some trial and error fiddling.
Counter-intuitively the attachment ContentDisposition object is READONLY which lead me to believe that I couldn't meddle in it however the read object is apparently a reference to the actual Attachment.ContentDisposition since setting values on the read instance does (apparently) correct the problem. Also used the Enum for MediaTypeNames (System.Net.Mime.MediaTypeNames.Text.Html) tho I don't think that was the issue.
Email send now looks like this :
private void SendMatchNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
// Create the file attachment for this e-mail message.
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mime.ContentDisposition disposition = att.ContentDisposition;
disposition.DispositionType = "attachment";
disposition.Inline = false;
disposition.FileName = "SeniorInfo.html";
disposition.CreationDate = DateTime.Now;
disposition.ModificationDate = DateTime.Now;
disposition.ReadDate = DateTime.Now;
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}

insert a link in to a email send using c#

I develop a program to send emails automatically using c#, and I want to insert a link to a web site to that email. How can I do it?
public bool genarateEmail(String from, String to, String cc, String displayName,
String password, String subjet, String body)
{
bool EmailIsSent = false;
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress(from, displayName);
m.To.Add(new MailAddress(to, displayName));
m.CC.Add(new MailAddress("xxx#gmail.com", "Display name CC"));
m.Subject = subjet;
m.IsBodyHtml = true;
m.Body = body;
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new
System.Net.NetworkCredential(from, password);
sc.EnableSsl = true;
sc.Send(m);
EmailIsSent = true;
}
catch (Exception ex)
{
EmailIsSent = false;
}
return EmailIsSent;
}
I want to send a link through this email. How should I add it to email?
You should be able to just add the mark-up for the link in your body variable:
body = "blah blah <a href='http://www.example.com'>blah</a>";
You shouldn't have to do anything special since you're specifying your body contains HTML (m.IsBodyHtml = true).
String body = "Your message : <a href='http://www.example.com'></a>"
m.Body = body;
Within the body. This will require that the body be constructed as HTML so the that a or can be used to render your link. You can use something like StringTemplate to generate the html including your link.
For some dynamic links, the email service providers will not show your link into email body if the link not prepend http (security issues)
like localhost:xxxx/myPage
m.body = "<a href='http://" + Request.Url.Authority + "/myPage'>click here</a>"

Categories

Resources