I want to send a dummy email from my server in .NET to my mail .
I am just sending mail without manipulation : Please let me know where I am going wrong . I have written my code as below :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SendingEmail.aspx.cs" Inherits="experiments_asp_SendingEmail" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h2>Send e-mail to someone#example.com:</h2>
<asp:Button Text="Submit" OnClick="sendMail" runat="server"/>
</form>
</body>
</html>
my .Net Code is shown as below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class experiments_asp_SendingEmail : System.Web.UI.Page
{
protected void sendMail(object sender, EventArgs e)
{
Console.Write("came here");
CreateTestMessage2("my college server"); //
}
public static void CreateTestMessage2(string server)
{
string to = "xyz#gmail.com";
string from = "xyz#gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
client.UseDefaultCredentials = true;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
}
Please let me know if any issues in this code , Do i need to add anything extra.
I am not getting any error when i click on submit.
Expectation : to send a dummy mail . Please note I am new to <
I believe that you need to supply more information to the SMTP server to accept your request. Lets take Gmail for example. I have taken your code and enabled it to distribute emails off of the google smtp server:
string to = "xyz#gmail.com";
string from = "xyz#gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = true;
NetworkCredential nc = new NetworkCredential("yourEmail#gmail.com", "yourPassword");
client.Credentials = nc;
try
{
client.Send(message);
MessageBox.Show("Your message was sent.");
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
As you can see you need to specify the active port the smtp server is listening on, and allow SSL message transfer. The other key part is providing acceptable credentials the SMTP server can validate a user against for authentication. Maybe your college server has a similar architecture. Do you manage the server, or does someone else?
Related
I am trying to send an email with C# code, copied from examples on MSDN (e.g. https://msdn.microsoft.com/en-us/library/14k9fb7t%28v=vs.110%29.aspx)
// from and password contain my credentials
// to contains a valid email address
public static void CodeExample()
{
try
{
using (MailMessage mail = new MailMessage(from, to))
{
using (SmtpClient server = new SmtpClient("smtp.googlemail.com"))
{
mail.From = new MailAddress(from);
mail.To.Add(new MailAddress(to));
mail.Subject = "Test subject";
mail.Body = "Test message";
mail.IsBodyHtml = false;
server.Port = 465;
server.Credentials = new System.Net.NetworkCredential(from, password);
server.UseDefaultCredentials = true;
server.EnableSsl = true;
server.ServicePoint.MaxIdleTime = 1;
server.Timeout = 60000;
Console.WriteLine("Sending to {0} by using SMTP host {1} port {2}.", to.ToString(), server.Host, server.Port);
server.Send(mail);
Console.WriteLine("mail Sent");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Inner Exception:");
Console.WriteLine(ex.InnerException?.ToString());
}
}
But I always get an exception:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException:
Unable to read data from the transport connection: net_io_connectionclosed.
The ‘from’ address details have been checked and seem OK. Sending from a Yahoo! account fails in the same way. I have tried lots of different combinations of SmtpClient properties. There are no messages in my firewall log.
Using Thunderbird, I can send from both the Googlemail and Yahoo! accounts without problems.
I would be grateful for any hints on how to get this to work.
Edit
I have seen this post SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
Google mail fails on port 587 (both using and commenting-out UseDefaultCredentials = true and EnableSsl = true), reporting that I have an insecure app. I will try Yahoo! on port 587 later.
Thanks for the help. Using port 587 was important, as shown at SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
I still cannot get smtp.googlemail.com or smtp.gmail.com to work, but that is covered at SmtpClient with Gmail.
My program is now working with smtp.mail.yahoo.com.
I want to create a button so that user can click and it will open a small new window where they can send email. This window will have "From", "To", "Subject", "Content" fields and all of that will have default text, user can edit them (except for "From" field). See image below:
What I tried:
I created an email form by:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<p>
From:<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</p>
To:<asp:Literal ID="Literal2" runat="server"></asp:Literal>
<p>
Subject:<asp:Literal ID="Literal3" runat="server"></asp:Literal>
</p>
Content:<asp:Literal ID="Literal4" runat="server"></asp:Literal>
</form>
</body>
</html>
Then I try to link this form with my current code:
Current code: I can send email by this code:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclientaddresshere");
mail.From = new MailAddress("defaultFromEmail#domain.com");
mail.To.Add("email1#yahoo.com,email2#yahoo.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail";
SmtpServer.Credentials = new System.Net.NetworkCredential("mysmtpserver#something.com", "");
SmtpServer.Send(mail);
Now I don't know is this right to use the form above for email window purpose? And how could I format and link all the fields to my working code?
What I have done is like this:
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
(Although I am using WinForms and not Windows Presentation Forms).
May this answer would help you.
Cheers!
**It just says " Failure sending mail."
Not sure its the problem with the code or SMTP server ? Please help here is my code, the variables are send through a form and i have confirmed that all variables are ok
SMTP Settings is in Web.config**
<?xml version="1.0"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="newsletter#abc.com">
<network host="mail.abc.com" port="25" userName="newsletter#abc.com" password="abc#!#"/>
</smtp>
</mailSettings>
</system.net>
<system.web>
</system.web>
</configuration>
Code in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdSend_Click(object sender, EventArgs e)
{
MailMessage mMailMessage = new MailMessage();
// address of sender
mMailMessage.From = new MailAddress(txtFrom.Text);
// recipient address
mMailMessage.To.Add(new MailAddress(txtTo.Text));
// Check if the bcc value is empty
if (txtBcc.Text != string.Empty)
{
// Set the Bcc address of the mail message
mMailMessage.Bcc.Add(new MailAddress(txtBcc.Text));
}
// Check if the cc value is empty
if (txtCc.Text != string.Empty)
{
// Set the CC address of the mail message
mMailMessage.CC.Add(new MailAddress(txtCc.Text));
} // Set the subject of the mail message
mMailMessage.Subject = txtSubject.Text;
// Set the body of the mail message
mMailMessage.Body = txtBody.Text;
// Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = true;
// Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal;
// Instantiate a new instance of SmtpClient
SmtpClient mSmtpClient = new SmtpClient();
// Send the mail message
try
{
mSmtpClient.Send(mMailMessage);
}
catch (Exception ex)
{
;//log error
lblMessage.Text = ex.Message;
}
finally
{
mMailMessage.Dispose();
}
}
}
Try using a telnet command to check if you can send a mail.
Start-> type "telnet":
open smtp.server.com 25
Helo smtp.server.com
Mail from:yourAdress#server.com
Rcpt to:yourAdress#server.com
Data
Subject:The life
OMG
.
Quit
If telnet isn't there, add it through add/remove windows features. See :http://technet.microsoft.com/en-us/library/cc771275(v=ws.10).aspx
First, we didn't the specify the SMTP server name:
SmtpClient smtp = new SmtpClient(#"abc.company.com");
Second, after specifying the SMTP server name like the snippet above, Make sure the firewall or Symantec (or some program like that) is not blocking the outbound request.
In your try catch block, you will need to go through all the exceptions. Keep looping until exception.innerexception is null. A more detailed error message will be found in the inner exception to why the mail message failed to be sent. The outer exception and corresponding message will be generic and not that useful.
Some samples can be found here:
Best way to check for inner exception?
Here some Psuedo Code
while (ex != null)
{
//LogThisException(ex);
ex = ex.InnerException;
}
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.
I am using the code as described in this question. However get following error when send an email.
Mailbox unavailable. The server response was: please authenticate to
use this mail server
Any ideas what could be wrong?
UPATE: Here is the code
System.Net.Mail.SmtpClient Client = new System.Net.Mail.SmtpClient();
MailMessage Message = new MailMessage("From", "To", "Subject", "Body");
Client.Send(Message);
With following in App.config.
<system.net>
<mailSettings>
<smtp from="support#MyDomain1.com">
<network host="smtp.MyDomain1.com" port="111" userName="abc" password="helloPassword1" />
</smtp>
</mailSettings>
</system.net>
The code posted there should work. if it doesn't, you might try setting the username and password in code-behind rather than reading them from the web.config.
Code sample from systemnetmail.com:
static void Authenticate()
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";
//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
//to authenticate we set the username and password properites on the SmtpClient
smtp.Credentials = new NetworkCredential("username", "secret");
smtp.Send(mail);
}
Yes, the smtp server is telling you that in order to relay email for you, you need to authenticate before attempting to send the email. If you have an account with the smptp server, you can set the credentials on the SmtpClient object accordingly. Depending on the authentication mechanism supported by the smtp server, the port, etc, will be different.
Example from MSDN:
public static void CreateTestMessage1(string server, int port)
{
string to = "jane#contoso.com";
string from = "ben#contoso.com";
string subject = "Using the new SMTP client.";
string body = #"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(server, port);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateTestMessage1(): {0}",
ex.ToString() );
}
}
The bottom line is that your credentials are not being passed to the Smtp server or else you wouldn't be getting that error.