I'm sending emails from my winforms app by using the MailMessage functionality.
I compile the email, save it to disk and then the default mail client will open the mail for the user to verify the settings before hitting Send.
I want to set the 'From' of the email automatically to the default email account as set up in the mail client. How can I do that?
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmailAccount);
mailMessage.To.Add(new MailAddress("recipient#work.com"));
mailMessage.Subject = "Mail Subject";
mailMessage.Body = "Mail Body";
If I leave fromEmailAccount blank I get an error, and if I set it to something like 'test#test.com' the email does not send as the local account does not have permissions to send it via an unknown account.
Get the user information from the OS (If windows 8, 10) them set the from to the user email, see this question: Get user information in Windows 8?
I have tested the following code and this seems to grab the local default mail from address and launches the mail message window, hope it helps:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace testMailEmailUser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Outlook.Application application = new Outlook.Application();
Outlook.AddressEntry mailSender = null;
Outlook.Accounts accounts = application.Session.Accounts;
foreach (Outlook.Account account in accounts)
{
mailSender = account.CurrentUser.AddressEntry;
}
Outlook.MailItem mail =
application.CreateItem(
Outlook.OlItemType.olMailItem)
as Outlook.MailItem;
if (mailSender != null)
{
mail.To = "someone#example.com; another#example.com";
mail.Subject = "Some Subject Matter";
mail.Body = "Some Body Text";
mail.Sender = mailSender;
mail.Display(false);
}
}
}
}
Related
I.m working on a Windows app where the user has to enter a password. I also have a "Forgot Password" link. on the window. When that's clicked, I have the user enter their email address and click a Submit button. Every time they enter an email address and click the button, I get the error message:
SmtpException has occured: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
The code I'm using is:
try
{
Cursor = Cursors.WaitCursor;
MailAddress from = new MailAddress("bgatt64#gmail.com", "Bob Gatto");
MailAddress to = new MailAddress("bgatto64#yahoo.com", "Bob Gatto");
MailMessage eMsg = new MailMessage(from, to);
eMsg.Subject = "Your Password Renewal Request";
eMsg.IsBodyHtml = true;
eMsg.Body = "This is the body.";
SmtpClient eClient = new SmtpClient("smtp.gmail.com", 587);
eClient.EnableSsl = true;
eClient.UseDefaultCredentials = true;gmail
// The following email and password used is that of my own gmail email
// that I use for my own personal email.
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<MyPassword>");
eClient.Send(eMsg);
}
catch (SmtpException ex)
{
throw new ApplicationException("SmtpException has occurred: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
What else needs to be done?
You cannot use your plain google account password to authenticate to Gmail SMTP server anymore as Google requires two-step authentication now.
You'll need to use the App Password instead:
Go to https://myaccount.google.com/security and turn on Two Step verification
Click "App Passwords"
Request a new password for the Mail application on the Windows Computer
You'll get the string with the 4 groups of characters. Now you need to use it in your code:
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<App Password>");
You can find more info Here
After the removal of less secure apps you can no longer use your actual google password to connect to the smpt server you need to create an apps password.
How to create a Apps Password for connecting to Google's SMTP server.
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "[redacted]#gmail.com";
private const string From = "[redacted]#gmail.com";
private const string GoogleAppPassword = "";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}
Note: if you are trying to connect users then you could also use Xoauth2 but using an apps password is far easer solution.
I have created one webpage in ASP.net with C#. In which I have put one button when this button clicks need to send mail. But, when I click on this button getting this exception :-
System.Net.Mail.SmtpException: Transaction failed. The server response was: 5.7.1 : Relay access denied at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message) at _Default.Button1_Click(Object sender, EventArgs e) in c:\Users\jay.desai\Documents\Visual Studio 2013\WebSites\WebSite2\Default.aspx.cs:line 47
Please refer below code:-
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;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("serveradmin.dmd#ril.com");
mail.Subject = "Pallet Shortage Emergency";
mail.To.Add("jay.desai#ril.com");
mail.Body ="Only 100 pallets are availabe in ASRS. This is system generated mail do not reply";
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
System.Net.NetworkCredential("serveradmin.dmd#ril.com", "1234");
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{ return true; };
smtp.Send(mail);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
The server error is indicating that it will not relay messages. Usually this means that you need to authenticate with the server before it will allow you to send email, or that it will only accept emails for delivery from specific source domains.
If you are always going to be sending to a single email domain then you can generally use the registered MX server for the domain. In this case (ril.com) the MX server list includes several primary mail servers, but the first one for me is: gwhydsmtp010.ril.com. I'd try that as the target mail server if your website is hosted outside the network that the mail server is on.
Alternatively you can provide SMTP login credentials to the SmtpClient object like this:
SmtpClient smtp = new SmtpClient("rmta010.zmail.ril.com",25);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("username", "password");
Logging in to the server will generally solve most 5.7.1 errors.
One final method that might be useful if you have admin rights on the Exchange server is to setup an SMTP connector to allow relay from a specific source address (your web server). I wouldn't recommend this however as any open relay is a Bad Idea(tm).
I am trying to send auto generated password through gmail to users but It is not working.
I have tried searching on many forums, this is the code I am using. Almost same given on every forum, still not working.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Net;
using System.Net.Mail;
/// <summary>
/// Summary description for GmailSender
/// </summary>
public class GmailSender
{
public GmailSender()
{
//
// TODO: Add constructor logic here
//
}
public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
{
try
{
NetworkCredential loginInfo = new NetworkCredential("mymail#gmail.com", "mypassword");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("mymail#gmail.com");
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
return true;
}
catch (Exception)
{
return false;
}
}
}
Can anyone help me out with this?
try this (for gmail smtp server).
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
Two day's ago I also had a similar problem. My web app just can't send mails throught gmail account, despite of correct port and credentials.
What helped me was to open my server through RDP and open this address: http://www.google.com/accounts/DisplayUnlockCaptcha
Here is some more info:
https://support.google.com/mail/answer/14257?hl=en
I am using visual studio 2010. When i run the asp page it shows the errors "The name 'txtname' doest not exists in the current context". I am new in C# programming needs help.
I am using all the defined variables but i am still confused why it is giving errors.
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;
using System.Net;
namespace WebApplication1
{
public partial class contactus : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("myinfo#yahoo.com");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("abc#gmail.com");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = txtName.Text + " : " + txtName1.Text;
msg.Body = txtMessage.Text;
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("abc#gmail.com", "paswword");
client.Credentials = credentials;
//Send the msg
client.Send(msg);
//Display some feedback to the user to let them know it was sent
lblResult.Text = "Your email has been received, you will be contacted soon by our representative if required.";
//Clear the form
txtName.Text = "";
txtName1.Text = "";
txtMessage.Text = "";
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again.";
}
}
}
}
When .cs file name in Code behind attribute does not match , then only this kind of error can occur.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Or it seems that you have copy and pasted the control or code related to it.
This often creates problem in designer file.
You can delete that textbox and once again drag-drop it on your app from toolbar
add runat="server" in the txtName control if it is a regular html control.
I know this is and old question. I got the same problem after copying few divs in a seperate place. This might be useful to anyone in future. Just remove runat="server" attribute of the relevenat tag and again insert it. It worked for me 100%.
**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;
}