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
Related
my search on the net always ended up with webclients or other clients than that for SMTP and was pointing me in an area of reference errors, which I couldn't resolve, as it does not seem to fit in my case, or I simply don't see the forrest for all the trees by now. Another hint of the order on UseDefaultCredentials didn't solve it either.
I have the following code, which I got from Stackoverflow and other tutorials on SMTP in C# which I intended to customize to my needs.
using System;
using System.Net.Mail;
namespace XXX
{
class SendMessage
{
MailMessage mail = new MailMessage("test2#domain.com", "test#domain.com");
SmtpClient client = new SmtpClient("mail.domain.com");
client.UseDefaultCredentials = false;
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//
//mail.Subject = "this is a test email.";
//mail.Body = "this is my test email body";
//client.Send(mail);
}
}
where things are "fuzzy" is the error I get from the compiler in VS2015, which states the name client.UseDefaultCredentials does not exist in the current context. The creation of the client does seem to work.
I was hoping to solve it by adding a using System.Net.Mail.SMTP; but that doesn't help.
I also get an invalid token '=' in class, struct,... but why?
You can't write code directly into your class you need a function or a method for it like this:
using System;
using System.Net.Mail;
namespace XXX
{
class SendMessage
{
public void sendEmailMessage(){
MailMessage mail = new MailMessage("test2#domain.com", "test#domain.com");
SmtpClient client = new SmtpClient("mail.domain.com");
client.UseDefaultCredentials = false;
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//
//mail.Subject = "this is a test email.";
//mail.Body = "this is my test email body";
//client.Send(mail);
}
}
}
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'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);
}
}
}
}
this is my problem:
I need to write a web service that, installed on a Server (server-1), can comunicate to a mail-Server (server-2).
The trick is: when I send a mail to the mail-server, since I have a PushNotificationSubscriber opened with it, the mailserver will send me the content of the First Mail it founds in the inbox.
But, the content will be written by the server in XML, and then comunicated to the Server-1.
The server-1 will also parse this XML to get Object type data to comunicate with a DB.
Is there a way to do this? Now I can Writedown my codes used:
SERVER-1 CODE:
using System;
using Microsoft.Exchange.WebServices.Data;
using System.IO;
using System.Xml;
using System.Text;
using System.Collections;
using System.Xml.Serialization;
using System.Web.Http;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.Credentials = new WebCredentials("mail_server_user", "mail_server_pass", "mail_server_domain");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.Url = new Uri("https://__Mail_Server's_URI__);
FindItemsResults<Item> findResults = service.FindItems(
WellKnownFolderName.Inbox,
new ItemView(1));
using (StreamWriter w = new StreamWriter("C:/Results.txt", false))
{
foreach (Item item in findResults.Items)
{
EmailMessage email = EmailMessage.Bind(service, item.Id);
email.Load();
w.WriteLine(item.Subject);
w.WriteLine(email.From.Address);
w.WriteLine(email.Body);
Console.WriteLine(item.Subject);
Console.WriteLine(email.From.Address);
Console.WriteLine(email.Body);
}
}
PushSubscription s = service.SubscribeToPushNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
new Uri("http://Server1_servicepage:XXXX_Port/api/SendNotification"),
1,
String.Empty,
new EventType[] { EventType.NewMail }
);
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
}
}
SERVER-2 CODE:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml.Serialization;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace NotificationAPI.Controllers
{
public class SendNotificationController : ApiController
{
[HttpGet]
public HttpResponseMessage Index()
{
HttpContent requestContent = Request.Content;
String stringContent = requestContent.ReadAsStringAsync().Result;
using (StreamWriter w = new StreamWriter("C:/received.txt", true))
{
w.WriteLine(stringContent);
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
}
As I said, I've tried many times, but I don't get where I am getting losing with it.
and since I'm new in C#, maybe, copy and pasting some code, I haven't done a good job :)
Also, If I have get it wrong, can someone explains me why is wrong? thanks in advice,
Daniel.
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%.