Adding an attachment to email using C# - c#

I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
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);
}

The message object created from your new MailMessage method call has a property .Attachments.
For example:
message.Attachments.Add(new Attachment(PathToAttachment));

Using the Attachment class as proposed in the MSDN:
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);

Correct your code like this
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
hope this will help you.
ricky

Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later
mail.Attachments.Add(new Attachment(file));
mail.Body = "body";

A one line answer:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));

Related

Send email using c#

I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion

Send Email from Alias Address using SMTP

This question has been asked so many times but I am still struggling to find a working solution.
Please consider the below code:
SmtpClient mailClient = new SmtpClient("outlook.office365.com");
MailMessage msgMail = new MailMessage();
msgMail.From = new MailAddress("validUser#domain.com", "displayName#aliasDomain.com");
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = new NetworkCredential("validUser#domain.com", "password");
mailClient.EnableSsl = true;
MailAddress sendMailTo = new MailAddress("someValidUser#someValidDomain.com", "Mark Twain")
msgMail.To.Add(sendMailTo);
msgMail.Subject = "Test Subject";
msgMail.Body = "Email content";
msgMail.IsBodyHtml = true;
mailClient.Send(msgMail);
msgMail.Dispose();
When someValidUser - the recipient - receives the email, I want it to show the display name : displayName#aliasDomain.com as opposed to the username registered to the validUser#domain.com account.
How can I achieve this?
Try adding the display name to the headers of the message:
msgMail.Headers.Add("Sender", "displayName#aliasDomain.com");
I hope this helps.
If you reset the from address in the MailMessage object you should be able to send from the alias email address. See below for the full code.
var fromAddress = new MailAddress("root#bobloblaw.com", "Root");
var toAddress = new MailAddress("plaintiff#gmail.com", "Plaintiff");
string fromPassword = "password";
string subject = "Your Lawsuit";
string body = "I regret to inform you...";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
From = new MailAddress("bob#bobloblaw.com", "Bob Lob")
})
{
smtp.Send(message);
}
This can work if you simply add an Alias to the Office 365 mailbox. Then use the Alias in the From field and the original username+password for the Credentials.
The recipients will see the name+alias you specify in the From field and not the username for the account. Just tried this with PowerShell Send-MailMessage as well as C#.

How attach mail template in .NET core

I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code
//From Address
string FromAddress = "info#gorollo.com";
string FromAdressTitle = "Gorollo";
//To Address
string ToAddress = email;
string Subject = subject;
string BodyContent = message;
var body = new BodyBuilder();
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress
(FromAdressTitle,
FromAddress
));
mimeMessage.To.Add(new MailboxAddress
(
ToAddress
));
mimeMessage.Subject = Subject;
using (var client = new SmtpClient())
{
client.Connect("smtp.mailgun.org", 587, false);
client.Authenticate(
"info#gorollo.com",
"password"
);
await client.SendAsync(mimeMessage);
await client.DisconnectAsync(true);
}
i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.
Example:
var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();

C# WPF - How to send an e-mail (to myself)?

for debugging purposes, I have globally handled all exceptions. Whenever an exception occurs, I silently handle it, and want to send myself an e-mail with the error details, so I can address this issue.
I have two emails, email1#gmail.com, and email2#gmail.com...
I have attempted using this code to send myself an e-mail, but it is not working.
string to = "email1#gmail.com";
string from = "email2#gmail.com";
string subject = "an error ocurred";
string body = e.ToString();
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.google.com");
client.Timeout = 100;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);
I have tried countless other pieces of code but I have no idea how to do it. Does anyone have a solid solution for this? Thanks a bunch.
This has to work. See more info here: Sending email in .NET through Gmail
using System.Net;
using System.Net.Mail;
//...
var fromAddress = new MailAddress("alextodorov01#abv.bg", "From Name");
var toAddress = new MailAddress("kozichka01#abv.bg", "To Name");
const string fromPassword = "fromPassword";
const string subject = "an error ocurred";
const string body = e.ToString();
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);
}
//...

Attach text file to mail using C# for Windows-mobile

I have this sample C# code for sending mail Through Windows-Mobile 6.5:
EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);
How to send for more than one mail address ?
How to attach text file to mail ?
Try this:
To attach file with more details like name/size.
Attachment attachment = new Attachment(outputFile, MediaTypeNames.Text.Html);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(outputFile);
disposition.ModificationDate = File.GetLastWriteTime(outputFile);
disposition.ReadDate = File.GetLastAccessTime(outputFile);
disposition.FileName = Path.GetFileName(outputFile);
disposition.Size = new FileInfo(outputFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
smtp.Send(message);
link for ref:
https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments%28v=vs.110%29.aspx
EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
//Adding more To address
message.To.Add(myrecipient2);
message.To.Add(myrecipient3);
//Adding more CC address
message.Cc.Add(myrecipient4);
message.Cc.Add(myrecipient5);
//Adding more Bcc address
message.Bcc.Add(myrecipient6);
message.Bcc.Add(myrecipient7);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
//Adding attachments
message.Attachments.Add("TextFilePath");
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);

Categories