Email Sender App with Images on Local Machine - c#

I have a small email application that lets a user build a message from checkboxes and then send the message as an email. I am trying to add an image to the email, i.e. a logo or signature. The application worked fine but as I was reseaching getting the images into the email, I found that I should be using System.Net.Mail instead of Interop. So I changed my email class to the code below. Now I'm not recieving the emails. I'm assumeing this is because the code is set-up for a server and I just want to run this on my local machine. This is just something I'm playing with to help me understand some concepts so real world use is not going to be a factor. I just want to be able to test my little program on my Outlook email account locally. My code is as follows...
using System;
using System.Net.Mail;
using System.Net.Mime;
namespace Email_Notifier
{
public class EmailSender:Notification
{
string emailRecipient = System.Configuration.ConfigurationManager.AppSettings ["emailRecipient"];
public void SendMail(string message)
{
try
{
string strMailContent = message;
string fromAddress = "MyApp#gmail.com";
string toAddress = emailRecipient;
string contentId = "image1";
string path = (#"C:Libraries/Pictures/Logo.gif");
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Email Notification";
LinkedResource logo = new LinkedResource( path , MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
// HTML formatting for logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:Logo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("localhost");
mailSender.Send(mailMessage);
}
catch (Exception e)
{
Console.WriteLine("Problem with email execution. Exception caught: ", e);
}
return;
}
}
}

You specify mailSender = new SmtpClient("localhost");.
Have you set up an SMTP server on your local machine? If not, you will need to do so to use SmtpClient. Otherwise, specify a hostname other than localhost, perhaps using your Gmail account as specified here, bearing in mind you will need to configure it for authentication and SSL.
See also the documentation for SmtpClient.
There are also one or two other issues I can see with your code - but let's deal with these after getting simple mail sending working.

if your problem is that you don't have a smtp server you are talking to on your machine, you will see an exception rather than just silently not having your email delivered (which i believe is what you are seeing given that you did not list an exception, but not completely sure). it could be that you are successfully delivering to your local smtp server, but it is failing to send the mail on. if you have the iis smtp server installed and that is what you are trying to use to send the mail, you can see failed email messages in the subdirectories of C:\Inetpub\mailroot. there is a badmail subdirectory that should have failed deliveries.
if you are on windows 7, it doesn't support the iis smtp server. an alternative for having an smtp server on your machine that doesn't actually deliver the email but does show you everything that has come through for any email address is http://smtp4dev.codeplex.com/. even if i do have the iis smtp server available in my operating system, i prefer this for development needs.

Related

When I want to send a email from a website published on Arvixe , where is the smtp server?

After I created a website on Arvixe, we'll call it
www.abcd.us
Accompanying the website, it also creates a email server called:
http://mail.abcd.us/
Because I need send email from this website, I created a email account named : wp#abcd.us
My question is : when I want to send an email from this website using c# code :
SmtpClient client = new SmtpClient("SERVER.arvixe.com", 465)
{
Credentials = new NetworkCredential("wp#abcd.us", "myAccountPassword"),
EnableSsl = true
};
MailAddress from = new MailAddress(#"wp#abcd.us", "wp");
MailAddress to = new MailAddress(#"ToAddress", "ToWho");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// set subject and encoding
myMail.Subject = "111";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
myMail.Body = "Hi test ";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
myMail.IsBodyHtml = true;
client.Send(myMail);
When run at this statement:
client.Send(myMail);
The code always fail to send. I guess the smtp server may be wrong.
"SERVER.arvixe.com", 465
But I do not know what the correct server is. Where smtp server after I create a website on Arvixe?
Based on what I can see from Arvixe's Knowledge Base, there are two options. If you want to use SSL, you will need to use mail.webeasyserve.com port 465. If you don't want to use SSL, then use mail.abcd.com port 26.
However, this knowledge base article is two years old, so it is possible the information is out of date. Hopefully it will point you in the right direction, even if it is no longer correct.
The domain can also be used as "localhost" and another mail port 25 (non SSL). The mail server at Arvixe can also be accessed by mail.yourdomain.com .

Sending out an automated email

I have an service that needs to send out automated emails on failures. I feel like i have it set up but i keep on receiving the following error:
Service not available, closing transmission channel. The server response
was: 4.3.2 Service not available
I cant quite figure out where i went wrong, but here is my code:
public static void AutoEmail()
{
try
{
SmtpClient newClient = new SmtpClient();
newClient.Host = "host name";
newClient.Port = Port number;
newClient.Credentials = new System.Net.NetworkCredential(
"username", "password");
MailMessage mail = new MailMessage();
mail.To.Add(new MailAddress("something#email.com"));
mail.Body = "This is a test message.";
mail.Subject = "Test - " + DateTime.Now;
mail.From = new MailAddress("something2#email.com");
newClient.Send(mail);
}
catch (Exception ex)
{
Log.WriteException("Error in Email", ex);
}
}
Any help would be much appreciated. Thanks!
Are you sure SMTP server you are using permits applications to send emails? I had met with similar issue and root cause was Exchange server was rejecting the send request due to insufficient permissions. And I have the same steps in my code as in yours. Check for permissions.
Have you tried
newClient .UseDefaultCredentials = true;
Does it help ?
The SMTP server name only works on a computer within the network that contains that SMTP server.
You need to make sure SMTP server's host name and port number in your program is correct. All the other code in your program seem fine.
I experienced the same error before. At the end, I changed to the correct host name and port number and everything works.
For example, Outlook.com Or Hotmail email accounts
host="smtp-mail.outlook.com" port="25" enableSsl="true"
https://www.outlook-apps.com/outlook-com-pop-settings/

Sending email from web site using Google Apps account

Been researching this issue for quite a while, but have yet to find any solution.
I can send email from the website using my regular gmail account using smtp.gmail.com as my host and port 587.
My current problem is that there's no problem sending the mail. I no longer receive an error. However, the email is never sent. Anyone have any ideas?
Here's the code:
Config:
<smtp from="admin#domain.com">
<network host="smtp.gmail.com" password="password" userName="admin#domain.com" port="587"/>
</smtp>
Code:
public void Send() {
bool bDev = ConfigurationManager.AppSettings["dev"] == "true";
MailMessage oMsg = new MailMessage();
foreach (string sAddress in To) {
if (sAddress != "") oMsg.To.Add(sAddress);
}
oMsg.From = ((FromName == null) || (FromName == "")) ?
new MailAddress(From) :
new MailAddress(From, FromName);
oMsg.Subject = Subject;
oMsg.Body = Body.ToString();
oMsg.IsBodyHtml = true;
oMsg.BodyEncoding = Encoding.UTF8;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = (new int[] { 587, 465 }).Contains(smtp.Port);
smtp.Send(oMsg);
}
I added a second To address and resumed testing. I began to receive email to both accounts. Then after removing the second address, it started working.
I ran into a new issue where my reply-to address was using the From address. So, I added additional code to set the reply address to that of the person's email address from my form.
Code
if (!string.IsNullOrEmpty(ReplyToAddress))
oMsg.ReplyTo = new MailAddress(ReplyToAddress);
However, I ran into an issue with Gmail ignoring my defined reply-to address, and using my from address. Apparently this is by design. I couldn't find any useful information on how to override this setting, so instead I did a workaround that might prove to be helpful to anyone else having this issue.
I created a generic email address with gmail (website#gmail.com) and setup a filter. Any emails coming from admin#domain.com need to be redirected to admin#domain.com.
Now, when I run my tests, all the emails are going where they are supposed to go AND the reply to field works great.
Not the best solution as it involves me remembering to setup a new account every time I run into this issue, but it's a solution that works for the time being until a better alternative comes up.
Had exactly same issue, that no error happened but also no email was sent. Google sometimes blocks your account(usually during testing). Try logging in into gmail account and see what it says.
UPD1: also check your sent folder in gmail.
UPD2: Also make sure that "From" email is the same as your gmail email address.

Is it possible to send an email programmatically without using any actual email account

I'm thinking of implementing "Report a bug/Suggestions" option to my game, however I am not quite sure how I could get that working. I do not have my own server or anything, so I can't just send the text that user has written to there.
The only way I came up with is that the client would write a message and I would send it to an email account where I could read them. However, I do not want that users would need to send the reports through their personal accounts. I am not quite sure how I could implement this and googling didn't bring up any good suggestions.
I haven't done a lot of network stuff, so I'd really appreciate it if you could explain ( possibly even in code ) the process step-by-step.
I am using C# and the game is being programmed for Windows Phone 7.
Yes, it is absolutely possible to do that. From a relatively low-level perspective, you need to:
Resolve the MX (mail-exchanger) server for the e-mail account you want to send to.
Open a socket to the MX server.
Send the appropriate SMTP commands to cause the e-mail message to be delivered to your recipient account. You essentially have the freedom to set the "from" address to be any arbitrary thing you want.
SMTP is a very simple/human-friendly protocol, so it's not a massive effort to do all of that by hand. At the same time, there are prebuilt libraries that will handle all of that for you (except possibly the resolution of the recipient's MX server).
Note that emails sent this way are more likely to be filtered out as spam (generally because the sender's IP/hostname is not going to match whatever domain you put on the outgoing e-mail address you decide to use).
Also note that since you can set the "from" address to anything, you have the option of asking the user if they want to provide their actual contact address, and if they do you can make that the "from" address so that you can actually get back in touch with them if necessary.
You don't need to use email at all. Consider using an error reporting service like sentry or airbrake.
These services have clients that you embed in your program; which automatically log your errors, including any debugging information/stacktrace; and notify you by email when your application reports a problem.
Usually you integrate the app's API into your own error handling mechanism. At the point of an error, the client will capture your debugging information, you can popup a modal asking user for information like "what were you doing when this error happened?", save that as part of your error response that is sent back to the service.
Since the app works over HTTP, you don't need any special ports to be open. It is easier and more helpful than having users send you emails with "it doesn't work!!", and you don't have to deal with email sending headaches.
I recently wrote an article on this: Sending email with C#
You basically have two choices, either you send it using an SMTP-client, this means that you have to have a SMTP-server and be able to connect to port 25 (if you're not using an external SMTP, then you have to manage that by yourself). Or you can use an external email provider, such as:
AlphaMail
SendGrid
Mandrill
If you're using AlphaMail you can send emails in the following way:
IEmailService emailService = new AlphaMailEmailService()
.SetServiceUrl("http://api.amail.io/v1/")
.SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
var person = new Person()
{
Id = 1234,
UserName = "jdoe78",
FirstName = "John",
LastName = "Doe",
DateOfBirth = 1978
};
var response = emailService.Queue(new EmailMessagePayload()
.SetProjectId(12345) // ID of AlphaMail project (determines options, template, etc)
.SetSender(new EmailContact("support#company.com", "from#example.com"))
.SetReceiver(new EmailContact("Joe E. Receiver", "to#example.org"))
.SetBodyObject(person) // Any serializable object
);
Another thing that differs from just building HTML and sending it with an SMTP-client is that with AlphaMail you have the ability to edit your emails outside your code directly in a GUI. You can also easily create highly dynamic templates using AlphaMail's templating language Comlang.
<html>
<body>
<b>Name:</b> <# payload.FirstName " " payload.LastName #><br>
<b>Date of Birth:</b> <# payload.DateOfBirth #><br>
<# if (payload.Id != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
So this is my thought, why don't you have the email sent to you...as you?
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name"); //Both the email addresses would be yours
var toAddress = new MailAddress("to#example.com", "To Name"); //Both the email addresses would be yours
const string fromPassword = "fromPassword";
const string subject = "There name or whatever";
const string body = "Errors ect....";
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);
}
code from here
All they would see would be the submit button so they wouldn't have all your personal username/password, also you should prolly set up a dummy account to have them sent to even if it just then forwards them to your real email account.
Another way to achieve this would be to host a WCF Service which takes in your Message and stores in db or /sends email. One downside of this is you'll need a web server to do this.
Try following code this might help you :
Dim objCDOMail
Set objCDOMail = Server.CreateObject("CDONTS.NewMail")
objCDOMail.From = "sender#domain.com"
objCDOMail.To = "receiver#domain.com"
objCDOMail.Subject = "Test Mail Script"
objCDOMail.BodyFormat = 0
objCDOMail.MailFormat = 0
objCDOMail.Body = "Testing Mail from Test Script"
objCDOMail.Importance = 1
objCDOMail.Send
Set objCDOMail = Nothing

ASP.Net Unable to send Email

I am trying to use the below code to send email from asp.net(C#).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using MovieReviews.Utils;
/// <summary>
/// Summary description for EmailUtil
/// </summary>
public class EmailUtil
{
public static void SendEmail(string to, string name, string from, string body)
{
try
{
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(from, name);
smtpClient.Host = "localhost";
//Default port will be 25
smtpClient.Port = 25;
//From address will be given as a MailAddress Object
message.From = fromAddress;
// To address collection of MailAddress
message.To.Add(to);
message.Subject = "Feedback";
message.IsBodyHtml = false;
// Message body content
message.Body = body;
// Send SMTP mail
smtpClient.Send(message);
}
catch (Exception ex)
{
Logger.LogError(ex);
throw ex;
}
}
}
When I try to execute it says
An attempt was made to access a socket in a way forbidden by its
access permissions 127.0.0.1:25
Please suggest me what should i do. I tried turning off the firewall as per some answers in the forums, but no luck.
Thank you in advance
for your code to work you need to have an SMTP server running on the local machine which accepts connections on 127.0.0.1, the exception implies that this either not the case or that some problem with priviliges and/or configuration exists.
EDIT:
Depending on your OS you could configure IIS to act as SMTP server. If you are on Windows 2008 then you need to use IIS 6 (contains SMTP server) additionally to IIS 7 (no SMTP server).
I had the same issue.
This port was blocked due to McAfee -> Access Protection -> Anti-virus Standard protection -> Prevent mass mailing worms form sending mail.
If you can remove that or any other AV protection you are fine.
If it is a protection policy over the organization then try switching port.
I've change the port to 81 in the Smtp4dev and in the C# application and it worked.

Categories

Resources