2015-12-10 12 views
7

Ho scritto un programma C# per inviare una e-mail, che funziona perfettamente. Inoltre, ho uno script PHP per inviare e-mail, che funziona perfettamente anche.Invio di e-mail dal web hosting senza dover utilizzare nome utente e password

Ma la mia domanda è: E 'possibile inviare una e-mail con C# come si fa da PHP in cui non è necessario specificare le credenziali, server, porte, ecc

Vorrei utilizzare C# invece di PHP, perché sto creando un'applicazione web ASP.Net.

Questo è il mio attuale codice 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); 

    } 
    } 
} 

Questo è come si è fatto in PHP:

<?php 
//define the receiver of the email 
$to = '[email protected]'; 

//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: [email protected]\r\nReply-To: [email protected]"; 

//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"; 
?> 

Non sto chiedendo per voi a scrivere il mio codice, ma forse si potrebbe fornire alcune informazioni o fammi sapere se è possibile o no.

Edit:

mia domanda non è di non utilizza un server smtp, ma come inviare una e-mail senza dover inserire username e password. So che funzionerà solo se la richiesta di inviare l'e-mail proviene dal mio server.

+3

realtà PHP * fa * Usa [Impostazioni vari server di posta elettronica] (http: // php. net/manual/en/mail.configuration.php), tuttavia sono memorizzati nel file php.ini e hanno valori predefiniti incorporati. Immagino che tu possa cambiarli in fase di esecuzione con 'ini_set()' se hai bisogno di apportare modifiche che non siano a livello di sistema. – Mike

+0

@Mike Non sapevo veramente cosa cercare, ma ho cercato spesso su google, forse per le cose sbagliate ... proverò i collegamenti che mi hai dato. client.UseDefaultCredentials = true; sembra promettente. – Creator

+0

In realtà ho rimosso il mio ultimo commento perché non penso che faccia quello che pensavo. Sembra che sia usato quando è necessario autenticarsi con il server di posta. Correggimi se sbaglio. Non conosco affatto C#. – Mike

risposta

11

Il motivo per cui in PHP è possibile inviare una mail senza specificare le credenziali SMTP è perché qualcun altro ha già configurato php.ini o sendmail.ini per te (i file che l'interprete PHP utilizza per ottenere alcuni valori).

Questo è solitamente il caso di un hosting gestito (o se si utilizza php sul proprio PC di sviluppo con strumenti come AMPPS che possono farti modificare facilmente le impostazioni SMTP attraverso un'interfaccia utente e averlo dimenticato).

In ASP.net/C# c'è la app.config o web.config file, dove è possibile iniettare impostazioni SMTP (nel tag <mailSettings>) e quindi raggiungere lo stesso risultato come PHP (il SmtpClient sarà utilizzare automaticamente le credenziali memorizzate lì).

Vedi queste domande per un esempio:

SmtpClient and app.config system.net configuration

SMTP Authentication with config file's MailSettings

+0

E questa è esattamente una risposta. Il server PHP deve essere già configurato da qualcuno, per far funzionare 'mail'. – yergo

+0

Inoltre, si potrebbe affermare che potrebbe scalfire le credenziali se è configurato un SMTP che non richiede autenticazione. –

1

A questi post, a cui probabilmente questo sarà un duplicato, troverete un paio di modi per inviare e-mail utilizzando ASP.NET.

Nota: Non è possibile inviare e-mail senza un server smtp, anche se non hai bisogno di uno proprio se qualcun altro consentono di utilizzare i loro di.

+0

gli piace mandare email senza usare smtp –

+0

@GoudaElalfy Aggiornato la mia risposta, e un server smtp è necessario da qualche parte ... anche con php. – LGSon

+0

@LGSon l'ho ottenuto dal link Come inviare email nel collegamento ASP.NET C# che mi hai dato. L'unica cosa divertente è che occorrono 30 minuti per ricevere l'email. ma suppongo che non abbia nulla a che fare con il codice ma con il server. – Creator

1

Se avete php installato nel server si può semplicemente inviare email tramite funzione principale php. Non hai bisogno di credenziali.

Il built-in e-mail funzione di invio di PHP è

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

È possibile utilizzare questo codice per il dettaglio comprensione

// recipients 
    $to = "[email protected]"; // 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' <'[email protected]'>' . "\r\n"; 
    $headers .= 'From: Admin | Hello Softs <[email protected]>' . "\r\n"; 


    // Mail it 
    mail($to, $subject, $message, $headers); 
1
Host : localhost 
OS : Ubuntu 12.04 + 
Language : PHP 

Installare sendmail nel vostro sistema operativo

sudo apt-get install sendmail 

Creare un file test-mail.php
codice Scrivi interna:

<?php 
$to  = '[email protected]'; 
$subject = 'Test Mail'; 
$message = 'hello how are you ?'; 
$headers = 'From: [email protected]' . "\r\n" . 
    'Reply-To: [email protected]' . "\r\n" . 
    'X-Mailer: PHP/' . phpversion(); 

if(mail($to, $subject, $message, $headers)){ 
    echo "Mail send"; 
}else{ 
    echo "Not send"; 
} 

echo "Now here"; 
?> 

mail verrà inviato [email protected]

Nota: don; t bisogno scrivere username/password.

1

È possibile configurare la sezione delle impostazioni di posta all'interno del file web.config nell'applicazione Web come mostrato di seguito. Se il tuo sito è ospitato da una società di hosting di terze parti, puoi chiedere loro i dettagli smtp (nome utente smtp, password smtp, nome server o IP e numero di porta). Se hai questa configurazione in web.config e smtp è abilitato (sul server), allora dovresti essere in grado di inviare e-mail senza specificare le credenziali nel codice C#.

<system.net> 
    <mailSettings> 
     <smtp from="[email protected]"> 
     <network password="password01" userName="smtpUsername" host="smtp.server.com" port="25"/> 
     </smtp> 
    </mailSettings> 
</system.net> 
0

Puoi inviare la posta senza SMTP o "senza avere" le credenziali: No ..

Se non si desidera scrivere le credenziali nei file php (in fase di sviluppo) è possibile utilizzare .env

https://github.com/vlucas/phpdotenv

esempio .env di file:

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' 

quindi è possibile utilizzare queste variabili env nei vostri file php:

getenv('SMTP_USER') 

Inoltre è possibile cripta il file .env o impostare senza accesso del pubblico .Ma questi non il più importante preoccupazioni di sicurezza che qualcuno dovrebbe preoccuparsi sono. . Se qualcuno riesce a entrare nel server, si è già in difficoltà ..

io non sono uno sviluppatore .NET MVC, ma si può set environmental variables (in fase di sviluppo) anche

in ogni caso è necessario scrivere da qualche parte o sono già stati scritti .. E non è un grosso problema per la sicurezza se non lo pubblichi ur codice da qualche parte come GitHub ecc ..

NOTA CHE: avere le variabili ambientali può causare problemi di prestazioni nella produzione soprattutto con php

Problemi correlati