send an email using SMTP without password in C#

落爺英雄遲暮 提交于 2019-12-22 11:04:21

问题


I have a web application using ASP.net and C#,in one step it will need from the user to send an email to someone with an attachments. my problem is when the user will send the email i don't want to put their password every time the user send. i want to send an email without the password of the sender. any way to do that using SMTP ? and this is a sample of my code "not all". the code is worked correctly when i put my password , but without it ,it is not work, i need a way to send emails without put the password but in the same time using smtp protocol.

private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
//  mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;               
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
} 

回答1:


I believe this can be accomplished easily, but with some restrictions.

Have a look at the MSDN article on configuring SMTP in your config file.

If your SMTP server allows it, your email object's from address may not need to be the same as the credentials used to connect to the SMTP server.

So, set the from address of your email object as you already are:

mail.From = new MailAddress(emailFrom);

But, configure your smtp connection one of two ways:

  1. Set your app to run under an account that has permission to access the SMTP server
  2. Include credentials for the SMTP server in your config, like this.

Then, just do something like this:

using (SmtpClient smtp = new SmtpClient())
{
    smtp.Send(mail);
}

Let the configuration file handle setting up SMTP for you. This is also great because you don't need to change any of your code if you switch servers.

Just remember to be careful with any sensitive settings in your config file! (AKA, don't check them into a public github repo)



来源:https://stackoverflow.com/questions/42845060/send-an-email-using-smtp-without-password-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!