【问题标题】:Sending email from webhosting without having to use username and password从虚拟主机发送电子邮件而无需使用用户名和密码
【发布时间】:2016-03-15 12:23:07
【问题描述】:

我编写了一个 C# 程序来发送电子邮件,效果很好。 此外,我有一个用于发送电子邮件的 PHP 脚本,效果也很好。

但我的问题是: 是否可以像使用 PHP 一样使用 C# 发送电子邮件,而无需指定凭据、服务器、端口等。

我想使用 C# 而不是 PHP,因为我正在创建一个 ASP.Net Web 应用程序。

这是我当前的 C# 代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net.Mail;
using System.Net;

namespace $rootnamespace$
{
public partial class $safeitemname$ : Form
{
    public $safeitemname$()
    {
        InitializeComponent();
    }

    private void AttachB_Click(object sender, EventArgs e)
    {
        if (AttachDia.ShowDialog() == DialogResult.OK)
        {
            string AttachF1 = AttachDia.FileName.ToString();
            AttachTB.Text = AttachF1;
            AttachPB.Visible = true;
            AttachIIB.Visible = true;
            AttachB.Visible = false;
        }
    }

    private void AttachIIB_Click(object sender, EventArgs e)
    {
        if (AttachDia.ShowDialog() == DialogResult.OK)
        {
            string AttachF1 = AttachDia.FileName.ToString();
            AttachIITB.Text = AttachF1;
            AttachPB.Visible = true;

        }
    }





    private void SendB_Click(object sender, EventArgs e)
    {
        try
        {
            SmtpClient client = new SmtpClient(EmailSmtpAdresTB.Text);
            client.EnableSsl = true;
            client.Timeout = 20000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(EmailUserNameTB.Text, EmailUserPasswordTB.Text);
            MailMessage Msg = new MailMessage();
            Msg.To.Add(SendToTB.Text);
            Msg.From = new MailAddress(SendFromTB.Text);
            Msg.Subject = SubjectTB.Text;
            Msg.Body = EmailTB.Text;

            /// Add Attachments to mail or Not
            if (AttachTB.Text == "")
            {
                if (EmailSmtpPortTB.Text != null)
                    client.Port = System.Convert.ToInt32(EmailSmtpPortTB.Text);

                client.Send(Msg);
                MessageBox.Show("Successfuly Send Message !");
            }
            else 
            {
                Msg.Attachments.Add(new Attachment(AttachTB.Text));
                Msg.Attachments.Add(new Attachment(AttachIITB.Text));
                if (EmailSmtpPortTB.Text != null)
                client.Port = System.Convert.ToInt32(EmailSmtpPortTB.Text);

                client.Send(Msg);
                MessageBox.Show("Successfuly Send Message !");
            }


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void settingsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        this.Validate();
        this.settingsBindingSource.EndEdit();
        this.tableAdapterManager.UpdateAll(this.awDushiHomesDBDataSet);

    }

    private void awDushiHomesEmail_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'awDushiHomesDBDataSet.Settings' table. You can move, or remove it, as needed.
        this.settingsTableAdapter.Fill(this.awDushiHomesDBDataSet.Settings);

    }
  }
}

这就是它在 PHP 中的实现方式:

<?php
//define the receiver of the email
$to = 'test@hotmail.com';

//define the subject of the email
$subject = 'Test email with attachment';

//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));

//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('PDFs\Doc1.pdf')));

//define the body of the message.
ob_start(); //Turn on output buffering
?>

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="Doc1.pdf" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();

//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?> 

我不是要你写我的代码,但也许你可以提供一些信息或者让我知道它是否可能。

编辑:

我的问题不是不使用 smtp 服务器,而是如何在不输入用户名和密码的情况下发送电子邮件。我知道,只有当发送电子邮件的请求来自我的服务器时,它才会起作用。

【问题讨论】:

  • 实际上 PHP 确实 使用various mail server settings,但是它们存储在 php.ini 文件中并具有内置的默认值。如果您确实需要进行非系统范围的更改,我假设您可以在运行时使用 ini_set() 更改它们。
  • @Mike 我真的不知道要找什么,但我用谷歌搜索了很多,也许是错误的东西......我会试试你给我的链接。 client.UseDefaultCredentials = true;看起来很有希望。
  • 实际上我删除了我的最后一条评论,因为我认为这并没有像我想象的那样。当您需要对邮件服务器进行身份验证时,似乎会使用它。如果我错了纠正我。我根本不懂 C#。
  • 您提供了一些代码并陈述了一个目标,但您没有说明您的代码的行为方式与您的预期不符。它会抛出错误吗?什么错误?
  • PHP 并不神奇。你也必须告诉它邮件服务器在哪里。

标签: c# php asp.net email


【解决方案1】:

在 PHP 中您可以在不指定 SMTP 凭据的情况下发送邮件的原因是其他人已经为您配置了 php.ini 或 sendmail.ini(php 解释器用来获取某些值的文件)。

这通常是托管主机的情况(或者如果您在开发 PC 上使用 php 和 AMPPS 等工具,可以让您通过 UI 轻松编辑 SMTP 设置并忘记它)。

在 ASP.net / c# 中有 app.configweb.config 文件,您可以在其中注入 smtp 设置(在 &lt;mailSettings&gt; 标记中)和因此实现与 PHP 相同的结果(SmtpClient 将自动使用存储在那里的凭据)。

请参阅以下问题以获取示例:

SmtpClient and app.config system.net configuration

SMTP Authentication with config file's MailSettings

【讨论】:

  • 这正是一个答案。 PHP 服务器必须已由某人配置,才能使 mail 工作。
  • 另外,您可以声明,如果配置了不需要身份验证的 SMTP,他可能会刮擦凭据。
【解决方案2】:

在这些帖子中,您可能会发现一些使用 ASP.NET 发送电子邮件的方法。

注意:您无法在没有 smtp 服务器的情况下发送电子邮件,但如果其他人让您使用他们的服务器,则您不需要自己的服务器。

【讨论】:

  • 他喜欢不使用 smtp 发送电子邮件
  • @GoudaElalfy 更新了我的答案,并且在某个地方需要一个 smtp 服务器......即使使用 php。
  • @LGSon 我通过你给我的如何在 ASP.NET C# 中发送电子邮件链接让它工作了。唯一有趣的是它需要 30 分钟才能收到电子邮件。但我想它与代码无关,而是与服务器有关。
  • 我的问题不是关于不使用 smtp 服务器,而是如何在无需输入用户名和密码的情况下制作它。感觉更节省我。我知道它现在只有在请求发送时才有效电子邮件来自我的服务器。
  • @Creator 好的,是的,邮件有时可能需要一些时间才能通过...... :)......我很高兴你找到了一个可行的解决方案。
【解决方案3】:

如果您的服务器中安装了 php,您可以简单地通过 php main 函数发送电子邮件。您不需要凭据。

php内置的邮件发送功能是

mail($to,$subject,$message,$header);

您可以使用此代码进行详细了解

// recipients
  $to  = "hello@hellosofts.com"; // note the comma
  // subject
  $subject = 'Testing Email';

  // message
    $message = " Hello, I am sending email";

  // To send HTML mail, the Content-type header must be set
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

  // Additional headers
  $headers .= 'To: 'Zahir' <'zahir@hellosofts.com'>' . "\r\n";
  $headers .= 'From: Admin | Hello Softs <do-not-reply@Hellosofts.com>' . "\r\n";


  // Mail it
  mail($to, $subject, $message, $headers);

【讨论】:

    【解决方案4】:
    Host : localhost
    OS : Ubuntu 12.04 +
    Language : PHP
    

    在您的操作系统中安装 sendmail

    sudo apt-get install sendmail
    

    创建一个文件test-mail.php
    里面写代码:

    <?php
    $to      = 'test_to@abc.com';
    $subject = 'Test Mail';
    $message = 'hello how are you ?';
    $headers = 'From: test_from@abc.com' . "\r\n" .
        'Reply-To: test_from@abc.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    
    if(mail($to, $subject, $message, $headers)){
        echo "Mail send";
    }else{
        echo "Not send";
    }
    
    echo "Now here";
    ?>
    

    邮件将发送至 test_to@abc.com

    注意:您不需要写用户名/密码。

    【讨论】:

      【解决方案5】:

      您可以在 Web 应用程序的 web.config 文件中配置邮件设置部分,如下所示。如果您的站点由第三方托管公司托管,您可以向他们询问 smtp 详细信息(smtp 用户名、smtp 密码、服务器名称或 IP 和端口号)。如果您在 web.config 中有此配置并且启用了 smtp(在服务器上),那么您应该能够发送电子邮件而无需在 c# 代码中指定凭据。

      <system.net>
          <mailSettings>
            <smtp from="you@yoursite.com">
              <network password="password01" userName="smtpUsername" host="smtp.server.com" port="25"/>
            </smtp>
          </mailSettings>
      </system.net>
      

      【讨论】:

        【解决方案6】:

        您可以在没有 SMTP 或“没有”凭据的情况下发送邮件吗:否..

        如果您不想在 php 文件中写入凭据(在开发阶段),您可以使用.env

        https://github.com/vlucas/phpdotenv

        示例.env 文件:

        DB_HOST='example'
        DB_PORT='example'
        DB_USER='postgres'
        DB_PASS='example'
        SMTP_HOST='example'
        SMTP_PORT='example'
        SMTP_USER='example'
        SMTP_PASS='example'
        HOST='example'
        

        然后你可以在你的 php 文件中使用这些环境变量:

        getenv('SMTP_USER') 
        

        您还可以加密 .env 文件或设置不公开访问权限。但这些并不是人们应该关心的最重要的安全问题。如果有人闯入您的服务器,那么您已经有麻烦了..

        我不是 .NET MVC 开发人员,但您也可以set environmental variables(处于开发阶段)

        无论如何,您需要将它们写在某个地方,或者它们已经写好了。除非您将代码发布在 github 等地方,否则这不是一个大的安全问题。

        注意:具有环境变量可能会导致生产中的性能问题,尤其是使用 php

        【讨论】:

          猜你喜欢
          • 2019-01-20
          • 1970-01-01
          • 2014-03-03
          • 1970-01-01
          • 2020-05-15
          • 2016-08-16
          • 2023-03-10
          • 1970-01-01
          • 2018-03-03
          相关资源
          最近更新 更多