insert a link in to a email send using c# - 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>"

Related

How to add a string to a HTML file while sending it as email in asp .net

I am working with asp .net. I want to send an authentication code to user's email when he sign up. I'm using this code to send email. I'm adding a html file to send. How can I add the authentication code to this HTML file?
This is the code which I used to send the html file via Email. So how can I add a string(authenticationCode) to HTML file to send it to the user for authentication.
var fromAddress = new MailAddress("hamza230#gmail.com", "From Hamza");
var toAddress = new MailAddress("usama90#gmail.com", "To Usama");
const string fromPassword = "****";
const string subject = "email";
const string body = "hello world";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = subject;
message.Body = body;
message.BodyEncoding = Encoding.UTF8;
String plainBody = "Title";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainBody, Encoding.UTF8, "text/plain");
message.AlternateViews.Add(plainView);
MailDefinition msg = new MailDefinition();
msg.BodyFileName = "~/newsletter.html";
msg.IsBodyHtml = true;
msg.From = "usamaazam10#gmail.com";
msg.Subject = "Subject";
ListDictionary replacements = new ListDictionary();
MailMessage msgHtml = msg.CreateMailMessage("usamaazam10#gmail.com", replacements, new LiteralControl());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, Encoding.UTF8, "text/html");
LinkedResource logo = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/logo.jpg"), MediaTypeNames.Image.Jpeg);
logo.ContentId = "logo";
htmlView.LinkedResources.Add(logo);
LinkedResource cover = new LinkedResource(System.Web.HttpContext.Current.Server.MapPath("~/images/cover.jpg"), MediaTypeNames.Image.Jpeg);
cover.ContentId = "cover";
htmlView.LinkedResources.Add(cover);
message.AlternateViews.Add(htmlView);
smtp.Send(message);
You can do this for small html pages
string smalHhtml = "<body>"
+ "your some designing"
+ "your Code : " + code
+ "</body>";
Note: This is for small body html and sending verification code via email is usually small html.
You can add the authentication code to the message body, for example:
...
message.Body = body + authenicationCode;
...
Or, if you don't create body as a const then you can create it at the top of your code, for example;
...
const string subject = "email";
string body = "Your authentication code is: " + authenicationCode;
...

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();

C# mail is not displaying link in my email

I am trying to send email with unsubsrible link in my aspx page. But when I check my email id It display only text. There was no link. Here is my code generate a email
string bodyContent = CKEditor1.Text;
string userLink = "http://www.abc.in/Message.aspx?action=rmsb&oldsubuser=";
string footerLink = "</br></br></br>You are receiving this mail because you have subscribed to our newsletter. If you do not wish to receive the mail, Click <a href='" + userLink + "" + ids[i].ToString() + "'>Here</a>";
bodyContent = bodyContent + footerLink;
EmailSend newsletter = new EmailSend();
newsletter.NewsLetterSend(ids[i].ToString(), bodyContent.Replace("'", "''"), txtSubject.Text.Replace("'", "''"));
//EmailSend.SendMailMessage("faredpt#gmail.com", ids[i].ToString(), "", "", txtSubject.Text, bodyContent);
bodyContent = bodyContent.Replace(footerLink, " ");
Here is the code for NewsLetterSend function
public void NewsLetterSend(string getemailAdd, string msgBody, string subject)
{
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("admin#abc.in", "admin#abc.in");
mail.To.Add(getemailAdd.Trim());
//set the content
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = msgBody;
mail.Priority = MailPriority.High;
//set the smtp settings
SmtpClient smtp = new SmtpClient("abc.in");
smtp.EnableSsl = false;
smtp.Credentials = new System.Net.NetworkCredential("admin#abc.in", "i#abc!23#");
//smtp.Port = 3535;
smtp.Port = 25;
//send email
smtp.Send(mail);
return;
}
Now this code is sending email successfully but unable to add link in my email. It show me simple text
Please tell me why this happening
You are replacing the quotation mark in href with two quotation marks!
Invalid statement: bodyContent.Replace("'", "''")
This will render your HTML invalid.
Could you try to replace </br></br></br> with <br/><br/><br/>? Probably because of invalid br tags your email is considered as not valid HTML and links become broken.

Email From ASP.net is going as HTML attachment

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.

Porting System.Web.Mail functionality to System.Net.Mail

The following function works perfectly:
protected void SendWebMailMessage(string DisplayName, string From, string ReplyTo,
string To, string Subject, string Body, string Attachments)
{
System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtpout.secureserver.net");
msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing",
2);
msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendusername", From);
msg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword",
mailpassword);
msg.To = To;
msg.From = DisplayName + "<" + From + ">";
msg.BodyFormat = MailFormat.Html;
msg.Subject = Subject;
msg.Body = Body;
msg.Headers.Add("Reply-To", ReplyTo);
SmtpMail.SmtpServer = "smtpout.secureserver.net";
SmtpMail.Send(msg);
}
However, I get a build warning telling me that System.Web.Mail is obsolete, and
that I should be using System.Net.Mail. So I used System.Net.Mail, and I came up with
the following function to replace my old one:
protected void SendNetMailMessage(string DisplayName, string From, string ReplyTo,
string To, string Subject, string Body, string Attachments)
{
MailAddress addrfrom = new MailAddress(From, DisplayName);
MailAddress addrto = new MailAddress(To);
MailAddress replytoaddr = new MailAddress(ReplyTo);
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = addrfrom;
msg.To.Add(addrto);
msg.ReplyTo = replytoaddr;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtpout.secureserver.net");
smtp.Credentials = new NetworkCredential(From, mailpassword);
smtp.Send(msg);
}
I don't get any exceptions or errors, but my message never goes through. Can anyone
tell me what I might be doing wrong? Thanks in advance.
If I'm not wrong... you are using the Goddady hosting.
I'm also using it... and I have **relay-hosting.secureserver.net** as the SMTP server.
I don't know... may be can be something like that... or you have not set the Relay in your console.
I tested you code above an it works fine. I had to add the body and subject properties, but even without them I still received a blank email. I also tried with and without providing credentials, both worked.
Initially I hadn't changed your host string and did receive an exception with the message "Failure sending mail."

Categories

Resources