How to send email through IIS7? - c#

I'm trying to set up a SMTP server on my Windows 7 machine in IIS7. I have set it to "Deliver email to localhost, port 25, no authentication. But when I try to connect programmatically from my C# program, I get an error:
Failure sending mail", inner exception "No connection could be made because the target machine actively refused it 127.0.0.1:25
public static void SendEmail(MailMessage m) {
var smtp = new SmtpClient {
Host = "localhost",
Port = 25,
UseDefaultCredentials = true,
};
smtp.Send(m);
}
Why? What other secret switch do I have to flip?

For development purposes I use storing mails to filesystem, try this in the web.config
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="c:\temp\mails\" />
</smtp>
</mailSettings>

Sorry, but most of these answers were totally confusing and don't explain the problem . Here is what the problem is.
The "SMTP E-mail" in IIS 7, on both Windows 7 Professional and "real" web server like Windows Server 2008 is that SMTP E-mail is not a true "virtual SMTP server" or what Microsoft calls "Simple Mail Transfer Protocol (SMTP)". Its just a an interface that allows you to apps that to an SMTP server online. The virtual SMTP server we used to have on older Windows is now only available as an add-on on server operating systems using the "Server Manager" under Administrative Tools and clicking "add features". Thats not found on say Windows 7 Professional. Yet another Microsoft blunder!
However, you can still use the "SMTP E-mail" piece under IIs in development or even your Web Server to route mail out to a real SMTP server. Its not like the old days when both were one and the same and you could route email out and back to your local box, etc for testing. They let you store that locally but thats not much help to me. Thats why when in SMTP E-mail "localhost" doesn't work. Thats what most people are saying. For that you would need to install third party software. A better solution is to just get the Windows Server Admin pack which has the virtual server and all the web server goodies found on the server OS and install that: http://www.sysprobs.com/install-admin-pack-windows-7-remote-desktop-manager
Keep in mind, you don't have to run ANY real SMTP virtual server on either your local box or on the server as long as you have an address to a real SMTP service (like "mail.yourwebhost.com"). Under IIS7, just click your SMTP E-mail piece under IIS7 and type in the address. But "localhost" wont wor'k. Usng SMTP E-mail with a remote host, I've found most SMTP or email providers require two additional things: a port other than "25", and you adding custom authentication credentials found under SMTP E-mail. Network Solutions likes to use your email address for the login and your address password. I hooked all that up and the mail c# object sent out mail without a virtual SMTP server on my local box. Last trick is be sure to also add this to your c# code:
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(
"mail.yourhost.com",155);//add custom port here
//This object stores the authentication values
System.Net.NetworkCredential mycredentials = new System.Net.NetworkCredential(
"yourname#yourdomain.com", "passwordhere");
client.UseDefaultCredentials = false;
client.Credentials = mycredentials;

Best method I found was to use SMTP4Dev, which listens for emails, and shows you what was "sent", but doesn't actually send anything. Great for testing!

You need to setup SMTP server in IIS7, here are the instructions how to setup:
http://learn.iis.net/page.aspx/751/configure-smtp-e-mail-in-iis-7/

Related

Sending e-mail through C#, Exchange and EWS Managed API gives error 407: Request failed - Proxy authentication required. Why?

I am writing a Windows forms application based on C# and the EWS Managed API 2.2.0 (Microsoft.Exchange.WebServices.dll assembly) for a client of mine who works on a company.
The app's logic is simple: My client puts his e-mail address "sender#ABC.domain.com" and the recipient's e-mail address "recipient#contoso.com" and the app sends an HTML-based e-mail to the recipient.
The app must connect to the Exchange Server of my client's company, authenticate my client to Exchange as a Windows domain user (using Windows domain authentication) (client is already logged in Windows with his username "sender" and as this Windows user makes the request) and then, send the E-Mail through his mailbox "sender#ABC.domain.com".
I have wrote the above code so far which seems to be correct, but it gives me this error: "The request failed. The remote server returned an error: (407). Proxy Authentication required"
try{
//Initialize and bound 'service' to the latest known version of Exchange
ExchangeService service = new ExchangeService();
//Use the Windows logged-in user domain account credentials:
//Is this correct / is this enough???
service.UseDefaultCredentials = true;
ServicePointManager.ServerCertificateValidationCallback = myValidationCallBackFunction;
service.AutodiscoverUrl("sender#ABC.domain.com", myRedirectionCallback);
MessageBox.Show("Autodiscover Exchange URL found:" + service.Url.ToString());
//Impersonation test - just in case - but this is not make any difference in the error
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "sender#ABC.domain.com");
//Initialize and set an EmailMessage
EmailMessage message = new EmailMessage(service);
message.Subject = "HelloWorld";
string emailMessageBody = "<!DOCTYPE html><html> ... </html>";
message.Body = new MessageBody(BodyType.HTML, emailMessageBody);
email.ToRecipients.Add("recipient#contoso.com");
message.SendAndSaveCopy();
MessageBox.Show("E-Mail sent successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
My client uses Windows 10. His PC is part of a Windows domain with url "XYZ.domain.com" and his username on Windows is "sender". He also has an Outlook app installed in his PC which connects perfectly to the Exchange Server on his company's network...
I am totally amateur with Windows domain accounts / authentication. Is this a Windows domain authentication problem? Is this an Exchange conection settings problem? Or the problem is in my code in the authentication section (do I have to add something more)?
I found a part of solution by my own!
Now my code works fine.
The problem was in the Proxy Settings in Windows 10 on my client's PC. For some reason he had Manual proxy setup enabled but he didn't know it. When I found it and disabled it, then the e-mail was sent fine.
I'm saying that I found "a part" of solution because:
1) The Outlook 365 works fine with the on premises Exchange Server 2010, even if I have the proxy settings enabled or not. But my app works only with proxy settings disabled. Does anyone know how this is explained? Why Outlook works fine with both ways?
2) If the IT of the company of my client forces him to have always enabled the proxy settings, how can I bypass this error? Do I have to pass somehow the User's credentials (with or without password)? If, yes, then how can I do this with C#?
I think it works fine both ways because your customer has "Don't use the proxy server for local (intranet) addresses" enabled in Windows 10 Proxy Settings. That would explain why the proxy is bypassed when connecting to the on-premise Exchange Server.
It doesn't explain however why that doesn't happen when your app connects to the local Exchange Server (?)
You can configure EWS to use a System.Net.WebProxy like this:
WebProxy myProxy = new WebProxy("http://myproxy", 8080)
{
BypassProxyOnLocal = true,
Credentials = new NetworkCredentials("username", "password)
};
exchangeService.WebProxy = myProxy;
What credentials you use depends on your client's Proxy infrastructure. If it requires a domain account you can set myProxy.UseDefaultCredentials = true to pass in the current user.
Hth

Can I send SMTP email through Office365 shared mailbox?

We are thinking about moving to O365; however, we developed software that uses our current Exchange server to send email both to external users as well as to a support box when errors occur.
I've been testing this to ensure that the code we have in place will continue to work with O365 but so far, I have not been very successful.
I have tried using .Net's SmtpClient as well as MailKit's SmtpClient and neither one seems to work. I keep getting error (this is the error from MailKit -- the .Net error is similar)
"AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful [*.prod.exchangelabs.com]"
I can use the credentials that I have in my code to log into OWA -- so I know the credentials are valid. Is it not possible to send email via O356? Is there any special configuration that has to happen in Exchange to make this possible?
Here is what I've tried so far:
MailKit
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress("Support","support#mydomain.com"));
msg.To.Add(new MailboxAddress("Me","me#mydomain.com"));
msg.To.Add(new MailboxAddress("External User","euser#externaldomain.com"));
msg.Subject = "Test";
msg.Body = new TextPart("plain"){
Text = "Here is a message for you"
};
using(var client = new SmtpClient()){
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.AuthenticationMechanisms.Remove("XOAUTH2"); //Not sure what this does. Have tried with and without
client.Connect("smtp.office365.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
client.Authenticate(new NetworkCredential("support#mydomain.com", "supportPwd"));
client.Send(msg);
client.Disconnect(true);
}
The .Net SmtpClient code looked very similar to the MailKit code.
Is there a way to send through O365 with a licensed user? (code above)
Are there any special settings required in Exchange or on the licensed user to make this work? (If the answer to 1 is yes)
Is it possible to send email through a shared mailbox for which the credentialed user has Send As rights?
Update
I'm still getting the same error message. We do have MFA enabled for our domain users. However, we have a policy that does not require MFA for users when they are signing in from a trusted location (our org's IP). I also listed our IP as a Trusted IP. In my mind, MFA shouldn't be the issue here.
I know the credentials are correct. I copied them from the code and pasted them in to the login screen when signing into M365 -- and I got in just fine.
What am I doing wrong?
Yes, you can.
Usersettings:
Server-settings :
https://support.office.com/en-us/article/POP-IMAP-and-SMTP-settings-for-Outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
SMTP server name smtp.office365.com
SMTP port 587
SMTP encryption method STARTTLS
No, you cannot. You need a licenced user to send mail via SMTP.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_o365admin/set-up-smtp-relay-with-shared-mailbox/d7b98214-9564-432c-b098-525a98c529fb
A customer of ours has a newsletter system set up with TYPO3 and we had to create a new mailbox for this. However, a light one will suffice: instead of a Office 365 Business Premium we only assigned a Office 365 F1 licence.
Edit: also found this: Can Office365 shared mailbox use SMTP?
For anyone who is having similar issues, I found that my problem was a Conditional Access Policy. Microsoft provides a Baseline Policy: Block Legacy Authentication -- which had been turned on in our AAD.
In looking at the Policy, it is designed to BLOCK any authentication mechanisms that don't require MFA. This includes things like POP and SMTP. Once I disabled this policy, the code listed above worked just fine.
For me only disabling "Security defaults" helped.

Syntax error, command unrecognized. The server response was ''

I've looked at 3 or 4 questions here so far and they haven't helped yet.
I have set up SmarterMail 14.x on a client's machine. I know very little about setting up mail servers (I don't know why he thinks I do) but I have it installed, a domain set up pointing to the MX record, the port open (9998) and I am able to send email just fine from the web interface.
However, I can't send email from Sql or from C#. I created a quick and dirty app to allow me to enter the server, port, credentials, and to/from and I get this response every time:
[Inner Exception]
Unable to connect to the remote server
[Details]
System.Net.Mail.SmtpException: Failure sending mail. ---> > System.Net.WebException: Unable to connect to the remote server ---> > System.Net.Sockets.SocketException: No connection could be made because the > target machine actively refused it 204.12.49.188:25
I've tried multiple logins. I've also confirmed that SMTP is turned on and IMAP/POP3 is turned off. I'd post images of it but unfortunately I can't yet.
The code to send is below and it is about as simple as it gets:
SmtpClient client = new SmtpClient(ServerTextBox.Text, Convert.ToInt32(PortTextBox.Text));
NetworkCredential login = new NetworkCredential(UsernameTextBox.Text, PasswordTextBox.Text);
client.Credentials = login;
MailMessage message = new MailMessage(FromTextBox.Text, ToTextBox.Text, "Wine and Spirits Jobs Alerts", "Below are this week's job alerts: There are no job alerts at this time");
client.SendCompleted += HandleSendCompleted;
client.SendAsync(message, null);
I've also tried it locally on their VPS and on my machine. I've turned on and off the firewall and I've got a specific rule allowing outgoing traffic on 9998 (and you can log into the web interface remotely) so this isn't a matter of being able to contact it.
I'm at a loss of what to do. If someone can help??
EDIT: It's clear I was using the wrong port - 9998 instead of 25. Using port 25 now tells me either time out or that it was actively refused. The firewall does have specific rules for port 25 that allow all traffic, so it shouldn't be stopped.
EDIT 2: I've re-created the MX record on the domain and ensured it is pointing to the correct IP address. I've also re-created the domain in Smartermail and made sure SMTP is turned on, authentication is required, SSL is not, POP and IMAP are turned off, and that my login is correct. I've also tried turning on and off the firewall. No dice.
I finally solved the issue.
It had nothing to do with firewalls or the MX record or using/not using an IP address and everything to do with the fact that while port 25 was indeed assigned to SMTP and SMTP was indeed turned on, the IP address of the domain itself was NOT assigned to the SMTP configuration so SmarterMail wasn't actually monitoring the port.
Problem solved - email sends. Fun stuff! Thank you for everyone's responses!
Try setting SMTP mail server IP address in your mail sending code.
SmtpMail.SmtpServer = "your mail server name or IP address goes here";
SmtpMail.Send(Message);
Your can set this property at global level or in any Initialization code.
Reference : https://msdn.microsoft.com/en-us/library/system.web.mail.smtpmail%28v=vs.110%29.aspx

Not able to connect to SMTP port of server

I have following piece of code, usiong which I am trying to send an email. I am using another server as SMPTClient.
MailMessage message = new MailMessage();
message.To.Add(toEmailId);
message.Subject = "test Subject";
message.From = new System.Net.Mail.MailAddress("myid#xyz.com");
message.Body = "This is a system generated email. Please do not reply";
SmtpClient smtp = new SmtpClient("anotherservername");
smtp.Send(message);
While debuggin, I get error at last line. The error is:
An attempt was made to access a socket in a way forbidden by its access permissions SERVER IP :25
I found out from internet that My firewall might be blocking me to access that server's port, or is there any setting, configuration which I have missed. Apparently the applications deployed on that server are able to send emails. I am still building one to test.
Some servers perform authentication and authorization by checking if you've connected to POP server some time before connecting to SMTP. You should try first connecting and authenticating with POP and afterwards connecting to SMTP.
Historically, email clients first checked and then sent emails in Send&Receive routines, so this was used as poor mans authorization. Take a look at wikipedia article about POP before SMTP.
Another issue which caused this for some people is how server address is provided to SmtpClient. You should use constructor which explicitly provides port number instead of appending it to IP/hostname. I.e.
instead of new SmtpClient("123.123.123.123:25")
use new SmtpClient("123.123.123.123", 25)

Getting Error message "failure sending mail " while Sendmail using localhaost in C#

I'm trying to send mail from machine(Windows 7), which doesn't have IIS server and mail server but this machine is connected to LAN. Do we really need IIS server to send mail with localhost. Please help me to understand the concept of localhost, What are the pre-conditions are required to use "localhost" as SMTP server.
I tried with Gmail SMTP host, it was working fine without any issues.
Here is my Code :
SmtpClient client = new SmtpClient();
client.Host = "localhost";
client.Port = 25;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("Admin", "password");
client.UseDefaultCredentials = false;
try
{
client.Send(mail);
}
catch (Exception ex)
{
logger.LogInfo(ex.Message);
}
Thanks,
Delwin
You will need to use IIS/ mail server / something for sending from your local machine.
If you are just trying to test, then you can use this to help simulate it:
http://antix.co.uk/Projects/SMTP-Server-For-Developers
You can install Smtp4Dev if you want just to do some testing during development.
If I remember well SMTP was stripped from the latest versions of IIS, so you'll need to find another tool anyway.
You don't need smtp server, you can store mails in filesystem, set your development web.config like this :
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory
pickupDirectoryLocation="w:\razvoj\TestAndBuild\UnitTestMailSend" />
</smtp>
</mailSettings>
</system.net>
To send an email you need an SMTP server program. You either have one locally (i.e. "localhost", and handily for you there is one built into IIS), or you connect to a remote server.
If you don't like the idea of IIS I'm sure there are other SMTP servers you could use, but you'll need something if you wish to send locally.

Categories

Resources