Sending email from webhosting without having to use username and password

时间:2015-12-10 01:28:01

标签: c# php asp.net email

I have written a C# program to send an email, which works perfectly. Additionally, I have a PHP script to send emails, which works perfectly aswell.

But my question is : Is it possible to send an email with C# like you do from PHP where you don't need to specify credentials, server, ports, etc.

I would like to use C# instead of PHP, because I am creating an ASP.Net web application.

This is my current C# code:

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);

    }
  }
}

This is how it is done in 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";
?> 

I'm not asking for you to write my code but maybe you could provide some info or let me know if its possible or not.

Edit:

My question is not about not using a smtp server but how to send an email without having to enter username and password. I know, that it will only work if the request to send the email comes from my server.

6 个答案:

答案 0 :(得分:11)

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

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

在ASP.net / c#中有 app.config web.config 文件,您可以在其中注入smtp设置(在<mailSettings>标记中)因此获得与PHP相同的结果(SmtpClient将自动使用存储在那里的凭证。)

请参阅以下问题的示例:

SmtpClient and app.config system.net configuration

SMTP Authentication with config file's MailSettings

答案 1 :(得分:1)

在这些可能与之相关的帖子中,您将找到几种使用ASP.NET发送电子邮件的方法。

注意:如果没有smtp服务器,您就无法发送电子邮件,但如果其他人允许您使用自己的服务器,则不需要自己的电子邮件。

答案 2 :(得分:1)

如果您的服务器中安装了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);

答案 3 :(得分:1)

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

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

答案 4 :(得分:1)

您可以在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>

答案 5 :(得分:0)

是否可以在没有SMTP或&#34;的情况下发送邮件而无需&#34;凭据:否..

如果您不想在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文件中使用这些env变量:

getenv('SMTP_USER') 

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

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

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

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

相关问题