i want to send mail to any email address, how to do that using C#. i am working on local host.
System.Net.Mail.MailMessage message=new System.Net.Mail.MailMessage(
new MailAddress(EmailUsername), new MailAddress("toemailaddress"));
message.Subject = "Message Subject"; // E.g: My New Email
message.Body = "Message Body"; // E.g: This is my new email ... Kind Regards, Me
For the SMTP part, you can also use SmtpClient:
SmtpClient client = new SmtpClient(ServerIP);
client.Credentials = new System.Net.NetworkCredential(EmailUsername, EmailPassword);
client.Send(message);
Please consider accepting some answers. A 0% accepted rate is not great.
Edited to fix the silly mistakes. Serves me right for not checking the code first.
You can use the SmtpClient class and call Send (or SendAsync) with a MailMessage instance. Both these classes are in the System.Net.Mail namespace.
SmtpClient's default constructor uses the configuration from your app/web.config, but you can use other constructors to specify the SMTP settings you want.
// using System.Net.Mail;
SmtpClient client = new SmtpClient();
MailMessage mm = new MailMessage()
{
Subject = "Subject here",
Body = "Body here"
};
mm.To.Add("email#tempuri.org");
mm.From = new MailMessage("from#tempuri.org");
client.Send(mm);
just to add that, there is a really nice website with everything you should know about System.Net:Mail namespace
it is called:
http://www.SystemNetMail.com/
hope it helps someone like it's been helping me ever since :)
This is to send Email with Attachment
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Try this...
public static void Send(string pFrom, string pSubject, string pTo, string pBody)
{
System.Net.Mail.MailMessage loMail = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential loCredencial = new System.Net.NetworkCredential(MAIL_USERNAME, MAIL_PASSWORD);
loMail.To.Add(pTo);
loMail.Subject = pSubject;
loMail.From = new System.Net.Mail.MailAddress(pFrom);
loMail.IsBodyHtml = true;
loMail.Body = pBody;
System.Net.Mail.SmtpClient loSmtp = new System.Net.Mail.SmtpClient(MAIL_SMTP);
loSmtp.UseDefaultCredentials = false;
loSmtp.Credentials = loCredencial;
loSmtp.Port = MAIL_PORT;
loSmtp.Send(loMail);
}
If you're using ASP.Net MVC I would recommend that you have a look at MvcMailer
Use this.
private static void SendMail(string subject, string content)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("YOURMAİL");
mail.To.Add("MAİLTO");
mail.Subject = subject;
mail.Body = content;
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("YOURMAİL", "YOURMAİLPASSWORD");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
catch (Exception ex)
{
}
}
And don't forget to add ---using System.Net.Mail;---
Related
I have the following code I use to send emails from my application:
var config = DeserializeUserConfig(perfilAcesso.GetClientConfigPath() + "Encrypted");
using (SmtpClient client = new SmtpClient())
{
client.Host = config.GetClientSMTP();
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(config.GetClientEmail(), config.GetClientPassword());
using (MailMessage mail = new MailMessage())
{
mail.Sender = new MailAddress(config.GetClientEmail(), config.GetClientName());
mail.From = new MailAddress(config.GetClientEmail(), config.GetClientCompany());
mail.To.Add(new MailAddress("emailToReceive"));
mail.Subject = "[PME] SOS - Equipamento Parado";
mail.Body = "";
client.Send(mail);
MessageBox.Show("Email enviado com sucesso!");
}
}
I have set up three possible SMTP hosts for the user to choose from: Gmail ("smtp.gmail.com"), Outlook ("smtp.live.com") and Yahoo ("smtp.mail.yahoo.com").
When I try to send and email using a Yahoo account, this exception is thrown:
System.Net.Mail.SmtpException: Mailbox unavailable. The server response was: Requested mail action not taken: mailbox unavailable.
I know for a fact that when sending emails with Gmail and Outlook accounts, the method works perfectly, because I tried it several times.
What am I doing wrong? Any help will be greatly appreciated!
Step 1
client.Port = 587;
Step 2
go to https://login.yahoo.com/account/security
Step 3
enable Allow apps that use less secure sign-in
Step 4 : full code
using System;
using System.Net.Mail;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
using (SmtpClient client = new SmtpClient())
{
client.Host = config.GetClientSMTP();
client.EnableSsl = true;
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(config.GetClientEmail(), config.GetClientPassword());
using (MailMessage mail = new MailMessage())
{
mail.Sender = new MailAddress(config.GetClientEmail(), config.GetClientName());
mail.From = new MailAddress(config.GetClientEmail(), config.GetClientCompany());
mail.To.Add(new MailAddress(config.emailToReceive));
mail.Subject = "Test 2";
mail.Body = "Test 2";
var isSend = false;
try
{
client.Send(mail);
isSend = true;
}
catch (Exception ex)
{
isSend = false;
Console.WriteLine(ex.Message);
}
Console.WriteLine(isSend ? "All Greeen" : "Bad Day");
Console.ReadLine();
}
}
}
}
}
if you add the same emails
mail.To.Add(new MailAddress(config.emailToReceive));
mail.To.Add(new MailAddress(config.emailToReceive));
you will git Error
Bad sequence of commands. The server response was: 5.5.0 Recipient already specified
if you want to reuse MailMessage
mail.To.Clear();
Are you sure that your from/to addresses are correct?
From and sender have to be your Yahoo addresses.
Here's a sample that works:
public static void Main(string[] args)
{
using (SmtpClient client = new SmtpClient())
{
client.Host = "smtp.mail.yahoo.com";
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("my-yahoo-login", "yahoo-password");
using (MailMessage mail = new MailMessage())
{
// This works
mail.Sender = new MailAddress("my-email-address#yahoo.co.uk", "Tom Test");
mail.From = new MailAddress("my-email-address#yahoo.co.uk", "Tom Test");
mail.To.Add(new MailAddress("my-email-address#outlook.com"));
/* This does not
mail.Sender = new MailAddress("my-email-address#outlook.com", "Tom Test");
mail.From = new MailAddress("my-email-address#outlook.com", "Tom Test");
mail.To.Add(new MailAddress("my-email-address#yahoo.co.uk"));
*/
mail.Subject = "Test mail";
mail.Body = "Test mail";
client.Send(mail);
Console.WriteLine("Mail sent");
}
}
}
If you put your non-Yahoo address in Sender and From fields (the commented code) you'll get the same exception.
In my web project, I am trying to programmatically send the contents of a text file that exists within the project to a default email address. Are there any simple ways of doing this in C#?
Something like:
// Read the file
string body = File.ReadAllText(#"C:\\MyPath\\file.txt");
MailMessage mail = new MailMessage("you#you.com", "them#them.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
mail.Subject = "file";
// Set the read file as the body of the message
mail.Body = body;
// Send the email
client.Send(mail);
Let say your file is /files/file1.txt
So to read it Use :
var content = System.IO.File.ReadAllText(Server.MapPath("/files/file1.txt"));
And Send It by
MailMessage message = new MailMessage();
message.From = new MailAddress("your email address");
message.To.Add(new MailAddress("the target email address"));
message.Subject = "...";
message.Body = content;
var client = new SmtpClient();
client.Send(message);
Here you have an example:
MailMessage message = new MailMessage();
message.From = new MailAddress("from#from.be");
message.To.Add(new MailAddress("to#to.be"));
message.Subject = "Subject goes here.";
message.Body = File.ReadAllText("Path-to-file");
SmtpClient client = new SmtpClient();
client.Send(message);
You should read the mail outside of construction of the e-mail, but it's here just to show the reading of a file.
Kr,
I am trying to send an email through and C# application (Console). Actually I would like it to send an email to any type of email but for the time being if I can get it to send to a gmail account I would be happy enough.
I just want to be able to get this to send to a gmail account for the time being?
Whole Program:
namespace EmailAddress
{
class Program
{
static void Main(string[] args)
{
Program test = new Program();
test.email_send();
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("hg#gmail.com");
mail.To.Add("hg#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:/example1.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
}
New code: Doesn't hang but will not send the message to the inbox
static void Main(string[] args)
{
Program test = new Program();
//test.email_send();
test.CreateTestMessage4();
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("g#gmail.com");
mail.To.Add("g#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);//list of attachements
smtp.Port = 587;//google standard -- most of the time wouldn't not set
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("*","*");
smtp.Send(mail);
Console.WriteLine("-- Sending Email --");
Console.ReadLine();
}
Can someone try this code and see if it works. For some reason this isn't working so I would like to have someone's fresh perspective of this. I just call this in the main method for an instance of the class.
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your email address");
mail.To.Add("your email address");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);//list of attachements
//smtp.Port = 587;//google standard -- most of the time wouldn't not set
//smtp.EnableSsl = true;
//smtp.UseDefaultCredentials = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.Credentials = new System.Net.NetworkCredential("your address",
"your password");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("*", "*"); smtp.Send(mail);
Console.WriteLine("-- Sending Email --");
Console.ReadLine();
}
Your code is close:
MailMessage mail = new MailMessage();
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com")) {
mail.From = new MailAddress("haufdoug#gmail.com");
mail.To.Add("haufdoug#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
smtp.Send(mail);
}
Now, regarding some of your other questions.
Port 587 is used by Google only. Typically the mail server you connect to will tell you what port to use for SMTP mail; Google said there's is 587.
For sending through other servers you typically won't set the port number.
side notes:
SmtpClient implements the IDisposable interface. So it should be wrapped in a using clause to ensure it is properly disposed of when complete. Unless you are using the .SendAsync() method.
I changed the variable name from SmtpServer to smtp for two reasons. First, naming convention. Variables inside a method are recommended to be camel case (forExampleThis). Second, SmtpServer is a misnomer as the object is an SmtpClient. Those are very different things and it's just bad practice to misname things.
Can you try this, it's working for me:
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Port = 587;
SmtpServer.Host = smtp.gmail.com;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
I want to send a email through gmail server. I have put the following code but it is getting stuck while sending. Any idea please....
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
//create instance of smtpclient
SmtpClient smtp = new SmtpClient();
smtp.Port = 465;
smtp.UseDefaultCredentials = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
The xxxx.com is a mail domain in Google apps.
Thanks...
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
// The important part -- configuring the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Port = 587; // [1] You can try with 465 also, I always used 587 and got success
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
smtp.UseDefaultCredentials = false; // [3] Changed this
smtp.Credentials = new NetworkCredential(mail.From, "password_here"); // [4] Added this. Note, first parameter is NOT string.
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);
While Googling, I came across a similar code, that worked for me. I am posting that code here.
class GMail
{
public void SendMail()
{
string pGmailEmail = "fromAddress#gmail.com";
string pGmailPassword = "GmailPassword";
string pTo = "ToAddress"; //abc#domain.com
string pSubject = "Test From Gmail";
string pBody = "Body"; //Body
MailFormat pFormat = MailFormat.Text; //Text Message
string pAttachmentPath = string.Empty; //No Attachments
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
SmtpMail.SmtpServer = "smtp.gmail.com:465";
SmtpMail.Send(myMail);
}
}
Set
smtp.UseDefaultCredentials = false
and use
smtp.Credentials = new NetworkCredential(gMailAccount, password);
This have worked for me:
MailMessage message = new MailMessage("myemail#gmail.com", toemail, subjectEmail, comments);
message.IsBodyHtml = true;
try {
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Timeout = 2000;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassord");
client.Send(message);
message.Dispose();
client.Dispose();
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
BUT (as of the time of this writing - Oct 2017)
You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)
I realise this is an answer to a very old question, with lots of other good answers. I am posting this code to include some of the useful comments posted by other users such as Using Statements and newer methods where some answers have obsolete methods. This code was tested and working as of 11 July 2018.
If sending via your GMail Account ensure that Allow less secure apps is enabled from your control panel
Class Code C#:
public class Email
{
public void NewHeadlessEmail(string fromEmail, string password, string toAddress, string subject, string body)
{
using (System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage())
{
myMail.From = new MailAddress(fromEmail);
myMail.To.Add(toAddress);
myMail.Subject = subject;
myMail.IsBodyHtml = true;
myMail.Body = body;
using (System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
{
s.DeliveryMethod = SmtpDeliveryMethod.Network;
s.UseDefaultCredentials = false;
s.Credentials = new System.Net.NetworkCredential(myMail.From.ToString(), password);
s.EnableSsl = true;
s.Send(myMail);
}
}
}
}
Class Code VB:
Public Class Email
Sub NewHeadlessEmail(fromEmail As String, password As String, toAddress As String, subject As String, body As String)
Using myMail As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMail.From = New MailAddress(fromEmail)
myMail.To.Add(toAddress)
myMail.Subject = subject
myMail.IsBodyHtml = True
myMail.Body = body
Using s As New Net.Mail.SmtpClient("smtp.gmail.com", 587)
s.DeliveryMethod = SmtpDeliveryMethod.Network
s.UseDefaultCredentials = False
s.Credentials = New Net.NetworkCredential(myMail.From.ToString(), password)
s.EnableSsl = True
s.Send(myMail)
End Using
End Using
End Sub
End Class
Usage C#:
{
Email em = new Email();
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text");
}
Usage VB:
Dim em As New Email
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text")
Use Port number 587
With the following code, it will work successfully.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("abc#mydomain.com", "Enquiry");
mail.To.Add("abcdef#yahoo.com");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.
To solve this, please follow the steps mentioned at the following link.
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:
http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html
ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage();
smtpmsg.From.Email = "abcd#test.com";
smtpmsg.To.Add(To);
smtpmsg.Bcc.Add("vijay#indiagreat.com");
smtpmsg.Subject = Subject;
smtpmsg.BodyText.Text = Body;
smtpmsg.Send("mail.test.com", "abcd#sss.com", "user#1234", ActiveUp.Net.Mail.SaslMechanism.Login);
simple code works
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(address, password);
smtp.Send(mail);
I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}