7

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.

Marv
  • 748
  • 11
  • 27
Creator
  • 1,502
  • 4
  • 17
  • 30
  • 3
    Actually PHP *does* use [various mail server settings](http://php.net/manual/en/mail.configuration.php), however they are stored in the php.ini file and have built-in default values. I would assume you could change them at run time with `ini_set()` if you did need to make changes that are not system-wide. – Mike Dec 10 '15 at 01:36
  • @Mike I didn't really know what to look for but i googled a lot, maybe for the wrong things... i will try the links you gave me. client.UseDefaultCredentials = true; looks promising. – Creator Dec 10 '15 at 01:44
  • Actually I removed my last comment because I don't think that does what I thought it did. It appears that's used when you need to authenticate with the mail server. Correct me if I'm wrong. I don't know C# at all. – Mike Dec 10 '15 at 02:01
  • You provided some code and stated a goal, but you didn't say how your code isn't behaving as you expect it to. Does it throw an error? What's the error? – mason Dec 10 '15 at 02:38
  • @mason There is no error its working but i would like to make it like in php without having to specify an account , server or the rest. like the php code i posted "it works without entering email acount info , smtp server info" etc. how to do that in c# i cant figure out. – Creator Dec 10 '15 at 02:58
  • 3
    PHP isn't magic. You have to tell it where the mail server is too. – mason Dec 10 '15 at 03:39
  • Check my answer on how and what can be done. And the PHP code you posted use smtp in the `@mail()` mehtod which you can see a sample of here: http://www.w3schools.com/php/php_ref_mail.asp – Asons Jan 05 '16 at 21:19

6 Answers6

11

The reason why in PHP you can send a mail without specifying SMTP credentials is that someone else already configured php.ini or sendmail.ini for you (files that the PHP interpreter uses to get some values).

This is usually the case with managed hosting (or if you use PHP on your development PC with tools like AMPPS, which can make you easily edit the SMTP settings through a UI and forget it).

In ASP.NET / C# there is the app.config or web.config file, where you can inject SMTP settings (in the <mailSettings> tag) and therefore achieve the same result as PHP (the SmtpClient will automatically use the credentials stored there).

Check these questions for an example:

SmtpClient and app.config system.net configuration

SMTP Authentication with config file's MailSettings

fruggiero
  • 943
  • 12
  • 20
  • And this is exactly an answer. PHP server has to be already configured by someone, to make `mail` work. – yergo Jan 11 '16 at 14:23
  • Additionally you could state that he could scratch the credentials if an SMTP which doesn't need authentication is configured. – Manuel Zelenka Jan 12 '16 at 05:43
1

At these posts, to which likely this will be a duplicate of, you will find a couple of ways how to send email using ASP.NET.

Note: You can't send email without a smtp server, though you don't need one of your own if someone else let you use their's.

Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165
  • he like send email without using smtp – Gouda Elalfy Jan 05 '16 at 21:01
  • @GoudaElalfy Updated my answer, and a smtp server is needed somewhere ... even with php. – Asons Jan 05 '16 at 21:10
  • @LGSon i got it to work from the How to send email in ASP.NET C# link you gave me.the only funny thing is it takes 30 minutes to get the email. but i gues it had nothing to do with the code but with the server. – Creator Jan 09 '16 at 22:14
  • My question was not about not using a smtp server but how to make it without having to enter username and password.feels more save to me.what i know it will only work now if the request to send the email comes from my server. – Creator Jan 09 '16 at 22:23
  • @Creator Okay, and yes, it can sometime take time for mails to get through ... :) ... and I'm glad you found a working solution. – Asons Jan 09 '16 at 22:40
1

If you have php installed in your server you can simply send email through php main function. You don't need credentials.

The built-in email sending function of php is

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

You can use this code for detail understanding

// 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);
Zahirul Haque
  • 1,599
  • 17
  • 22
1
Host : localhost
OS : Ubuntu 12.04 +
Language : PHP

Install sendmail in your OS

sudo apt-get install sendmail

Create a file test-mail.php
Write code inside :

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

Mail will be sent to test_to@abc.com

Note : You don;t need to write username/password.

Monty
  • 1,110
  • 7
  • 15
1

You can configure the mail settings section within the web.config file in your web application as shown below. If your site is hosted by a third party hosting company, you can ask them for smtp details (smtp username, smtp password, server name or IP and the port number). If you have this configuration in web.config and smtp is enabled (on the server), then you should be able to send emails without specifying the credentials in c# code.

<system.net>
    <mailSettings>
      <smtp from="you@yoursite.com">
        <network password="password01" userName="smtpUsername" host="smtp.server.com" port="25"/>
      </smtp>
    </mailSettings>
</system.net>
TejSoft
  • 3,213
  • 6
  • 34
  • 58
0

Can you send mail without SMTP or "without having" credentials : No ..

If you don't want to write your credentials in your php files(in the development stage) you can use .env

https://github.com/vlucas/phpdotenv

example .env 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'

then you can use these env variables in your php files:

getenv('SMTP_USER') 

Also you can crypt the .env file or set no public access .But these aren't the most important security concerns someone should care.. If someone breaks into your server,you are already in trouble..

I'm not a .NET MVC developer but you can set environmental variables(in the development stage) too

Anyway you need to write them somewhere or they are already written..And it's not a big security concern unless you post your code somewhere like github etc..

NOTE THAT:having environmental variables may cause performance problems in the production especially with php