Created
March 14, 2017 16:37
-
-
Save Brad-Christie/282016282b0b743c6a4a077728aa1e81 to your computer and use it in GitHub Desktop.
Demonstrating attaching an image to a MailMessage from a url.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = "https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=abc%20123%20456&choe=UTF-8"; | |
var attachment = MailMessageHelper.GetUrlAsAttachment(url, "qrcode.png"); | |
message += string.Format("<img src='{0}' />", attachment != null ? "cid:" + attachment.ContentId : url); | |
using (SmtpClient client = new SmtpClient("xxx.xxx.x.xx")) | |
{ | |
MailAddress to = new MailAddress("john@example.com"); | |
MailAddress from = new MailAddress("email@example.com"); | |
MailMessage email = new MailMessage(from, to); | |
email.Subject = "Subject"; | |
email.Body = message; | |
email.IsBodyHtml = true; | |
try | |
{ | |
client.Send(email); | |
} | |
catch (Exception ex) | |
{ | |
Console.Write(ex); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net.Mail; | |
using System.Net; | |
public static class MailMessageHelper | |
{ | |
public Attachment GetUrlAsAttachment(string url, string attachmentName) /* using System.Net; */ | |
{ | |
try { | |
var uri = new Uri(url); | |
var request = (HttpWebRequest)WebRequest.Create(uri); | |
var response = (HttpWebResponse)request.GetResponse(); | |
var attachment = new Attachment(response.GetResponseStream(), attachmentName); | |
attachment.ContentDisposition.Inline = true; | |
return attachment; | |
} catch (UriFormatException uex) { | |
// Something wrong with the URL | |
return null; | |
} catch (WebException wex) { | |
// Something wrong with the URL, but according to the server. | |
// This could be a 404 (Not Found), 500 (Server error), etc. | |
return null; | |
} catch (Exception ex) { | |
// SOmething unanticipated went wrong. | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment