Send Email with C# - c#

I am using this code to send an email with an attachment when a button is clicked in my windows 8 application
For this I am using the EASendMail SMTP component which I had to install and reference in my app.
private async void btnSend_Click(object sender, RoutedEventArgs e)
{
btnSend.IsEnabled = false;
await Send_Email();
btnSend.IsEnabled = true;
}
private async Task Send_Email()
{
String Result = "";
try
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
// Set sender email address, please change it to yours
oMail.From = new MailAddress("test#emailarchitect.net");
// Add recipient email address, please change it to yours
oMail.To.Add(new MailAddress("support#emailarchitect.net"));
// Set email subject
oMail.Subject = "test email from C# XAML project with file attachment";
// Set Html body
oMail.HtmlBody = "<font size=5>This is</font> <font color=red><b>a test</b></font>";
// get a file path from PicturesLibrary,
// to access files in PicturesLibrary, you MUST have "Pictures Library" checked in
// your project -> Package.appxmanifest -> Capabilities
Windows.Storage.StorageFile file =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");
string attfile = file.Path;
Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
// if you want to add attachment from remote URL instead of local file.
// string attfile = "http://www.emailarchitect.net/test.jpg";
// Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
// you can change the Attachment name by
// oAttachment.Name = "mytest.jpg";
// Your SMTP server address
SmtpServer oServer = new SmtpServer("smtp.emailarchitect.net");
// User and password for ESMTP authentication
oServer.User = "test#emailarchitect.net";
oServer.Password = "testpassword";
// If your SMTP server requires TLS connection on 25 port, please add this line
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
// If your SMTP server requires SSL connection on 465 port, please add this line
// oServer.Port = 465;
// oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
await oSmtp.SendMailAsync(oServer, oMail);
Result = "Email was sent successfully!";
}
catch (Exception ep)
{
Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
}
// Display Result by Diaglog box
Windows.UI.Popups.MessageDialog dlg = new
Windows.UI.Popups.MessageDialog(Result);
await dlg.ShowAsync();
}
But when I click the button, I get an error message "Failed to send email with the following error: Access is denied"
How do I fix this?
EDIT:
After enabling the pictures library I know get this message:
EDIT:
I did some further work and noticed that the email send fine without the attachment.
It works without this code:
Windows.Storage.StorageFile file =
await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("test.jpg");
string attfile = file.Path;
Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
But I need the attachment to be sent also.
How do I fix this?

Related

LinkedResource fails in MailMessage with CC recipients, succeeds otherwise

I am developing a Windows Background Service with .NET and C#. It periodically queries a REST API and sends emails if certain conditions are met. Sometimes the data returned from the API will have image files and sometimes not. When image files are returned, the service embeds them into the email body before sending. I'm embedding the image file in four steps:
Download the image as a byte[]
Convert byte[] to MemoryStream
pass the stream to a new LinkedResource
Add the linked resource to the AlternateView for the MailMessage
This works if the message has a single "To" recipient and no CC or BCC recipients. The image displays correctly in the body of the email. The weird problem I'm having is that if I add multiple recipients in To, CC or BCC, the image fails to display in the email body. This problem seems to be limited to Outlook. I did a test with two recipients, one internal to the organization and one Gmail account. The image displayed correctly in Gmail but was broken in Outlook.
Here is the snippet of code where the service builds the LinkedResource and sends the email.
htmlBody = htmlBody.Replace("{incident_time}", incident.IncidentTime)
.Replace("{incident_type}", incident.IncidentType)
.Replace("{incident_location}", incident.IncidentLocation)
.Replace("{reporting_agency}", incident.ReportingAgency)
.Replace("{severity}", incident.Severity)
.Replace("{details}", incident.Details);
// embed attached images
var attachmentsResult = await arcGisRestClient.QueryAttachmentsAsync(
incidentSublayerUrl,
tokenResponse.Token,
objectId: incident.ObjectId);
IList<LinkedResource> linkedResources = new List<LinkedResource>();
if (!string.IsNullOrEmpty(attachmentsResult))
{
var attachmentsObj = JObject.Parse(attachmentsResult);
var attachments = FeatureAttachmentConverter.FromJObject(attachmentsObj);
// if attachments > 0
if (attachments.Count > 0)
{
string imgHtml = "";
foreach (var attachment in attachments)
{
string attachmentUrl = $"{incidentSublayerUrl}/{attachment.ParentObjectId}/attachments/{attachment.Id}?token={tokenResponse.Token}";
WebClient webClient = new WebClient();
byte[] bytes = webClient.DownloadData(attachmentUrl);
MemoryStream stream = new MemoryStream(bytes);
LinkedResource linkedResource = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
imgHtml += #"<img src='cid:" + linkedResource.ContentId + #"' width='450'/>";
linkedResources.Add(linkedResource);
}
htmlBody = htmlBody.Replace("{attachments}", imgHtml);
}
else
{
htmlBody = htmlBody.Replace("{attachments}", "");
}
}
AlternateView htmlAlternate = AlternateView.CreateAlternateViewFromString(htmlBody, new ContentType(MediaTypeNames.Text.Html));
foreach (var lr in linkedResources)
{
htmlAlternate.LinkedResources.Add(lr);
}
// create email
MailMessage message = new MailMessage
{
Subject = "TEST Incident Notification",
};
message.AlternateViews.Add(htmlAlternate);
string[] emailToAddresses = _config.GetSection("EmailNotificationTo").Get<string[]>();
message.To.Add(string.Join(',', emailToAddresses));
string[] emailCcAddresses = _config.GetSection("EmailNotificationCc").Get<string[]>();
message.CC.Add(string.Join(',', emailCcAddresses));
message.From = new MailAddress(_config["EmailNotificationFrom"]);
// send email
SmtpClient smtpClient = new SmtpClient("mail.domain.org", 25);
using (smtpClient)
{
smtpClient.Send(message);
logger.Info($"Email notification sent; objectid: {incident.ObjectId}");
}
Could this be an issue with our internal STMP server or Outlook settings rather than a problem with the above code?

error when trying to send email using smtp 'System.Net.Mail.SmtpException' in System.dll

trying to send a password recovery email using the smpt protocol in c# and for some reason I can't seem to get it right. I will highly appreciate it of someone could help.
This is what I was relying on. And Here's the code:
enter cpublic void sendEmailWithPass( string username , string email , string password)
{
try
{
var fromAddress = new MailAddress("xxx", "xxx");
var toAddress = new MailAddress(email, "CLIENT!");
const string fromPassword = "xxx";
string subject = "recover password";
string body = "heloo! \n according to your request your password is: \n " + password;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{ Subject = subject, Body = body })
{ smtp.Send(message); }
SendMessage("&answerForgotRequest&true!");
}
catch
{
SendMessage("&answerForgotRequest&failed!");
}
}
in addition, this is the line which corresponds to the error
public void answerServer(string message)
{
string ans = message.Split('&')[2];
if (ans.StartsWith("failed!"))
{
MessageBox.Show("an error was occured while trying sending the mail");
}
]
Since you are struggling with this, you need to at least try to catch the exception, no-one can help you as you are just throwing it away:
try
{
// email code
}
catch(Exception ex)
{
// breakpoint this line (yes look up online how to do it)
MessageBox.Show(Ex.ToString());
// write it to file if you need to
//File.WriteAllText("someFileName.Txt",Ex.ToString() );
}
Then when you have an actual exception, please paste it (or ask a new question) so we know what's happening.
You might want to have a look at these too:
Exception Handling (C# Programming Guide)
Navigate through code with the Visual Studio debugger

Sending email with attachments using Amazon AWS SMTP

I'm trying to send a email using amazon WS SMTP, is sending with success but i never receive the email. When i send it without attachment i receive it with success.
Here's my code
// Create an SMTP client with the specified host name and port.
using (SmtpClient client = new SmtpClient(ssHost, ssPort))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(ssSMTP_Username, ssSMTP_Password);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
MailMessage message = new MailMessage();
try
{
//creates a messages with the all data
message.From = new MailAddress(ssFrom, ssFromName);
//message.To.Add(ssTo);
//To
List<String> toAddresses = ssTo.Split(',').ToList();
foreach (String toAddress in toAddresses)
{
message.To.Add(new MailAddress(toAddress));
}
//cc
List<String> ccAddresses = ssCC.Split(',').Where(y => y != "").ToList();
foreach (String ccAddress in ccAddresses)
{
message.CC.Add(new MailAddress(ccAddress));
}
//bcc
List<String> BccAddresses = ssBcc.Split(',').Where(y => y != "").ToList();
foreach (String ccAddress in ccAddresses)
{
message.Bcc.Add(new MailAddress(ccAddress));
}
//replyTo
if (ssReplyTo != null)
{
message.ReplyToList.Add(new MailAddress(ssReplyTo));
}
//email
message.Subject = ssSubject;
message.Body = ssBody;
message.IsBodyHtml = true;
//Attachment
foreach (RCAttachmentRecord attchmentRec in ssAttachmenstList){
System.IO.MemoryStream ms = new System.IO.MemoryStream(attchmentRec.ssSTAttachment.ssBinary);
Attachment attach = new Attachment(ms, attchmentRec.ssSTAttachment.ssFilename);
message.Attachments.Add(attach);
ssErrorMessage = ssErrorMessage + "||" + attchmentRec.ssSTAttachment.ssFilename+"lenght:"+attchmentRec.ssSTAttachment.ssBinary.Length;
}
client.Send(message);
}
source: http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-net.html
I think your problem probably is that you are not adding your attachments correctly to your message.
I was successful sending a single message with an attachment. I started with the code that was taken directly from your source link above. I then added the code from another SO article about the missing content type problem.
The attachment is a Word Document Lebowski.docx from my Documents folder. I suggest you create a similar simple Word document and run the following code to verify you can send a simple attachment in a single email.
The following code worked successfully for me:
namespace SESTest
{
using System;
using System.Net.Mail;
namespace AmazonSESSample
{
class Program
{
static void Main(string[] args)
{
const String FROM = "from-email"; // Replace with your "From" address. This address must be verified.
const String TO = "to-email"; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
const String SUBJECT = "Amazon SES test (SMTP interface accessed using C#)";
const String BODY = "This email and attachment was sent through the Amazon SES SMTP interface by using C#.";
// Supply your SMTP credentials below. Note that your SMTP credentials are different from your AWS credentials.
const String SMTP_USERNAME = "user-creds"; // Replace with your SMTP username.
const String SMTP_PASSWORD = "password"; // Replace with your SMTP password.
// Amazon SES SMTP host name.
const String HOST = "your-region.amazonaws.com";
// The port you will connect to on the Amazon SES SMTP endpoint. We are choosing port 587 because we will use
// STARTTLS to encrypt the connection.
const int PORT = 2587;
// Create an SMTP client with the specified host name and port.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
try
{
Console.WriteLine("Attempting to send an email through the Amazon SES SMTP interface...");
var mailMessage = new MailMessage()
{
Body = BODY,
Subject = SUBJECT,
From = new MailAddress(FROM)
};
mailMessage.To.Add(new MailAddress(TO));
//REMOVE THIS CODE
//System.IO.MemoryStream ms = new System.IO.MemoryStream(attchmentRec.ssSTAttachment.ssBinary);
//Attachment attach = new Attachment(ms, attchmentRec.ssSTAttachment.ssFilename);
//mailMessage.Attachments.Add(attach);
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
contentType.Name = "Lebowski.docx";
mailMessage.Attachments.Add(new Attachment("C:\\users\\luis\\Documents\\Lebowski.docx", contentType));
client.Send(mailMessage);
Console.WriteLine("Email sent!");
}
catch (Exception ex)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + ex.Message);
}
}
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
}
}
Once you prove you can send an email with one attachment from your account, then you can start working on how to get the binaries from your ssAttachmentsList into an your emails and the correct content type assigned to each. But you didn't provide enough code or context for me to determine that at this time. Im hoping this code will help you get over your attachment issue.

Sending emails are not received outside the company using System.Net.Mail

I am using the following code in order to send emails. The emails are received successfully to the recipients at works but they are not received outside. I tried to send an email to my gmail account and same issue, I cannot received it.
At work, we are using Exchange 2010. I checked junk in gmail and no emails were found.
My Code:
public bool SendEmail()
{
try
{
var mailMessage = CreateMailMessage();
var client = new SmtpClient()
{
Credentials = new NetworkCredential(Resources.Username, Resources.Password, Resources.Domain),
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = ConfigurationProperties.ExchangeIPAddress
};
client.Send(mailMessage);
}
catch (Exception ex)
{
LogFile.Write(string.Format("EmailManager::SendEmail failed at {0}", DateTime.Now.ToLongTimeString()));
LogFile.Write(string.Format("Error: {0}", ex.Message));
return false;
}
return true;
}
private MailMessage CreateMailMessage()
{
var mailMessage = new MailMessage();
mailMessage.Subject = ConfigurationProperties.EmailSubject;
mailMessage.Body = ConfigurationProperties.EmailBody;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
LogFile.Write(string.Format("Subject= {0}", mailMessage.Subject));
LogFile.Write(string.Format("Body= {0}", mailMessage.Body));
AddRecipients(mailMessage);
return mailMessage;
}
Is there any property I am missing in order to let outside emails recipients for receiving the emails?
There's no property that you can set to allow the mails to go outside of your network. This sounds like a configuration on your Exchange server and nothing to do with System.Net.Mail.
You'll need to talk with your system administrator.

Why the message doesn't send to my outlook mail?

I am creating a website for user to fill out information. After completed fill out information, the user click button to submit a ticket and send email to me as a copy. However, I didn't receive any email after I click to send it. The submit ticket was successful except the email. We use Microsoft Outlook.
Anyone know why or I am missing something?
I did add the reference using Outlook = Microsoft.Office.Interop.Outlook;
C# codes,
protected void BtnIPAM_Click(object sender, EventArgs e)
{
//codes for submitting ticket then send email
string uid = Bam.NEAt.GetUserID();
try
{
//Create the Outlook application
Outlook.Application oApp = new Outlook.Application();
//Create the new message
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add a recipient
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("xxxxx#xxxx.com");
oRecip.Resolve();
//Set the basic properties
oMsg.Subject = "A Copy of IP Address Request";
oMsg.Body = "This is a test who sent by " + uid;
//Send the message
oMsg.Save();
oMsg.Send();
oRecip = null;
oMsg = null;
oApp = null;
}
catch {}
}
use this to send an email:
using System.Net;
public static void SendAlertEmail()
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("receive#whatever.com");
message.Subject = "Put Subject";
message.From = new System.Net.Mail.MailAddress("sender#whatever.com");
message.Body = "Body Message Here";
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.Host = "put host settings here";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.Send(message);
}
To call it use this:
SendAlertEmail();

Categories