Sending an email automatically using c# - c#

This is my first experience with sending an email using c#. Everything I have so far I got from reading and watching videos. I currently have the code written to send an email. It creates it and displays the email with all of the information correct and ready to send. The email opens up and then I click send and it works. The problem is that I want the email to send on its own, without me having to click send.
This is my code:
static void SendEmail()
{
Microsoft.Office.Interop.Outlook.Application app = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mailItem.Subject = "Status of Code";
mailItem.To = "bt#outlook.com";
mailItem.Body = "Code Ran Successfully";
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
}
I tried adding in
mailItem.Send;
but I kept getting an error. How else would I do this?

Referencing Microsofts documentation (https://msdn.microsoft.com/en-us/library/swas0fwc(v=vs.110).aspx), I'd recommend instead using an SMTP client (as opposed to being outlook specific).
Your code would then look something like:
public static void SendEmail()
{
string to = "bt#outlook.com";
string from = "fromAddress#outlook.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Code Ran Successfully";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in SendEmail(): {0}",
ex.ToString() );
}
}

Related

Configure forward-to property for MailMessage like replyto in C#

Is there any way to configure forward-to email address like replyto in System.Net.Mail.MailMessage?
If not then is there any way I can achieve that?
No, there is not.
The reason is that there is no such field defined in an email. You can see the defined fields here.
So this is not a matter of C# API, there is no way to do what you want to do, not in C# and not in other languages/frameworks.
You can do this only by doing it via Outlook (using interop)
var newItem = mailItem.Forward();
newItem.Recipients.Add("test#test.be");
newItem.Send();
the .Forward() is described here
There's no 'forwardto' in MailMessage (that's up to the user receiving the mail).
But you can send to multiple receipients at once, using either the CC or the BCC properties.
Here's an axample using CC:
public static void CreateCopyMessage(string server)
{
MailAddress from = new MailAddress("ben#contoso.com", "Ben Miller");
MailAddress to = new MailAddress("jane#contoso.com", "Jane Clayton");
MailMessage message = new MailMessage(from, to);
// message.Subject = "Using the SmtpClient class.";
message.Subject = "Using the SmtpClient class.";
message.Body = #"Using this feature, you can send an email message from an application very easily.";
// Add a carbon copy recipient.
MailAddress copy = new MailAddress("Notification_List#contoso.com");
message.CC.Add(copy);
SmtpClient client = new SmtpClient(server);
// Include credentials if the server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an email message to {0} by using the SMTP host {1}.",
to.Address, client.Host);
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateCopyMessage(): {0}",
ex.ToString() );
}
}
Now you can send to more than one, which Works like auto forwarding.

using gmail as smpt for deliver email from mvc controller

I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);

How to send mail from user's Outlook mailbox

Hi I know how to send the mail from smpt through below mailcode.But not getting any clue on how to send mail from user's outlook.so that user can find his mails in his sent items folder
Please help me..
Below is web config codes for sending the mail
<mailSettings>
<smtp>
<network host="11.111.111.1" port="25" defaultCredentials="true"/>
</smtp>
</mailSettings>
and this is my send mail method:
public static void SendMessage(string sbj, string bd, string bccadd, string attachFile1,string buyeremail)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
message.From = new MailAddress(buyeremail);
message.To.Add(new MailAddress(bccadd));
message.Subject = sbj.Trim();
message.Body = bd.Trim();
SmtpClient mysmptclient = new SmtpClient();
mysmptclient.DeliveryMethod = SmtpDeliveryMethod.Network;
message.Attachments.Add(new Attachment(attachFile1));
try
{
message.Attachments.Add(new Attachment(attachFile5));
}
catch
{
}
mysmptclient.Send(message);
}
I just modified my code as below :
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.NameSpace oNamespace = new Outlook.NameSpace("MAPI");
Outlook.MailItem oMailItem = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMailItem.HTMLBody = bd.Trim();
oMailItem.Subject = sbj.Trim();
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(bccadd);
oRecip.Resolve();
oMailItem.Send();
oRecip = null;
oRecips = null;
oMailItem = null;
oApp = null;
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
//string script = "<script>alert('" + ex.Message + "');</script>";
}
Bu now it shows error:
Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
Please help me
You can use the Microsoft Exchange Web Services (EWS) Managed API to create and send email messages.
http://msdn.microsoft.com/en-us/library/office/dd633628(v=exchg.80).aspx
Code shown on MSDN:
// Create an email message and identify the Exchange service.
EmailMessage message = new EmailMessage(service);
// Add properties to the email message.
message.Subject = "Interesting";
message.Body = "The merger is finalized.";
message.ToRecipients.Add("user1#contoso.com");
// Send the email message and save a copy.
message.SendAndSaveCopy();
I believe you'll need to use the outlook API's to perform that, since the MailObject and SMTP will send the mail internally using the mentioned params, something like this should help http://www.codeproject.com/Tips/165548/C-Code-snippet-to-send-an-Email-with-attachment-fr
A possible duplicate : Can only send email via Outlook if Outlook is open

How to send HTML email with Image using asp.net with c#

Hi all of you I try following code to send HTML email along with Image in HTML
but I can receive only text format mail not Image
public void HTML_mail(string mailTo,string mailSub,string mailMessage)
{
try
{
SmtpClient client = new SmtpClient();
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
//client.Host = "smtp.gmail.com";
//client.Port = 587;
//WITH SMTP Server with Authenticaton
client.Host = mailServer;
client.Port = Convert.ToInt16(serverPort);
// setup Smtp authentication
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(userName, passWord);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
MailMessage msg = new MailMessage();
msg.From = new MailAddress(userName);
msg.To.Add(new MailAddress(mailTo));
msg.Subject = mailSub;
msg.IsBodyHtml = true;
msg.Body = string.Format(mailMessage);
//HTML CODE "<html><head></head><body><p><h3>Dadu</h3></p><img src='http://localhost:2727/photo/mukeshwedsjashmin/1/Suresh2.jpg' height='500px' width='500px' alt='' /></body>"
try
{
client.Send(msg);
//lblMsg.Text = "Your message has been successfully sent.";
}
catch (Exception ex)
{
//lblMsg.ForeColor = Color.Red;
//lblMsg.Text = "Error occured while sending your message." + ex.Message;
}
}
catch(Exception ex)
{
}
}
I can Only see the "Dadu" in the mail
I choose display Image on my gmail A/C
You're email is referencing a localhost image, try it wih an online one as the image may not be available to the email.
Your email is referencing a local image:
http://localhost:2727/photo/mukeshwedsjashmin/1/Suresh2.jpg
The only e-mail receiver that will be able to see that image is yourself. No one else will have access to your local web server, thus won't be able to see the image.
You need to reference an image that is available to the public.
As a side note
In my experience, sending emails like this from a local mail server, especially if the email contain HTML and images, will almost certainly be caught as spam. I prefer to send my emails through an email delivery service. I only have experience with Postmark, which has a good .Net library, but I bet there are other great services as well.

How to send the mail from c#

I have code,
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(oMailMessage);
(all variables have values)
I have installed SMTP virtual services. why it is unable to send emails. why it is not working ??
EDIT
public bool SendMail(string strToEmailId, string strFromEmaild, string strSubject, string strBody)
{
try
{
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "SERVERNAME";
SmtpMail.Send(oMailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
I have this code. It is executing fine and is returning true, but I'm not getting any email in the inbox.
What else could be wrong?
Getting some mails in BadMail Dir at C:\Inetpub\mailroot\Badmail also in Queue Directory getting some mails here ... what does that means..??
I found that mail only can sent to gmail accounts... why it is?
As mentioned by others, your code is fine and is most likely something in your SMTP configuration or maybe your email client your sending your test emails to is marking them as spam. If it's spam, well that's easy enoughto figure out.
If it's something with the email, you can go to your mailroot folder and their will be some folders there with the email files along with a description. See if there's anything in the BadMail folder or the queue folder and open them up in notepad and view what error is given for why they weren't sent.
Determine what the error is:
try
{
SmtpMail.Send(oMailMessage);
}
catch (Exception ex)
{
//breakpoint here to determine what the error is:
Console.WriteLine(ex.Message);
}
From here, please edit your question with that exception details.
Its hard to tell, but one possibility is that you haven't enabled anonymous access on the SMTP virtual server. Go to the the virtual server properties dialog, select the Access tab, click the Access Control button, and make sure that Anonymous Access is enabled.
There doesn't appear to be anything functionally wrong with your program. It's likely a configuration issue between your program and the mail server. I would try the following to diagnose the problem.
Wrap the code in a try/catch block and see if the exception message contains useful data
Use 127.0.0.1 instead of localhost just to rule out anything crazy
Ensure your SMTP server is running on the standard port (25 I believe)
Hello you can follow the following code:
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("your gmail id", "password");
MailMessage msg = new MailMessage();
msg.To.Add(textBoxTo.Text);
msg.From = new MailAddress("your gmail id");
msg.Subject = textBoxSubject.Text;
msg.Body = textBoxMsg.Text;
Attachment data = new Attachment(textBoxAttachment.Text);
msg.Attachments.Add(data);
client.Send(msg);
MessageBox.Show("Successfully Sent Message.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
have you tried 127.0.0.1 instead of Localhost?
Also have you tested that the SMTP service is working, check out this link for details.
In the virtual smtp server Add relay restrictions and connection control so that none of the outside connections are allowed

Categories

Resources