Click here to Skip to main content
13,147,812 members (39,791 online)
Click here to Skip to main content
Add your own
alternative version

Stats

159.1K views
10.7K downloads
150 bookmarked
Posted 4 Jun 2008

Email Sender

, 12 Jun 2011
Rate this:
Please Sign up or sign in to vote.
Send email directly to the receiver's SMTP server.

sender.png

Introduction

Usually, when we send an email, we need to login to a known email service provider's SMTP server and deliver the email using that server. If we add the send email functionality to a software, the user needs to configure an SMTP server address, the username, and the password. Why not send an email to the receiver's SMTP server directly? Because the receiver's server doesn't need authorization, otherwise you can only receive email when the sender knows your account password. I think many programmers have been asking this question, so I explored the issue.

The problem is we don't know which SMTP server is responsible for receiving emails for a given email address. The secret is that this information can be obtained from Domain Name System (DNS) servers. This seems simple; however, it needs a lot work to implement the DNS protocol (RFC 1035) because the .NET Framework doesn't support getting mail server info from DNS. Once we have the SMTP server address, we can send emails to the receiver directly!

Using the code

I partially implemented the DNS protocol in four classes: DnsMessage, DnsQuery, DnsResource, and DnsMessageCoder. Then, I wrapped the functionality in the DomainNameUtil class.

Now, EmailSender can use DomainNameUtil to get the mail server from the email address and send the email:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace QiHe.CodeLib.Net
{
    public class EmailSender
    {
        /// <summary>
        /// Default SMTP Port.
        /// </summary>
        public static int SmtpPort = 25;

        public static bool Send(string from, string to, string subject, string body)
        {
            string domainName = GetDomainName(to);
            IPAddress[] servers = GetMailExchangeServer(domainName);
            foreach (IPAddress server in servers)
            {
                try
                {
                    SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
                    client.Send(from, to, subject, body);
                    return true;
                }
                catch
                {
                    continue;
                }
            }
            return false;
        }

        public static bool Send(MailMessage mailMessage)
        {
            string domainName = GetDomainName(mailMessage.To[0].Address);
            IPAddress[] servers = GetMailExchangeServer(domainName);
            foreach (IPAddress server in servers)
            {
                try
                {
                    SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
                    client.Send(mailMessage);
                    return true;
                }
                catch
                {
                    continue;
                }
            }
            return false;
        }

        public static string GetDomainName(string emailAddress)
        {
            int atIndex = emailAddress.IndexOf('@');
            if (atIndex == -1)
            {
                throw new ArgumentException("Not a valid email address", 
                                            "emailAddress");
            }
            if (emailAddress.IndexOf('<') > -1 && 
                emailAddress.IndexOf('>') > -1)
            {
                return emailAddress.Substring(atIndex + 1, 
                       emailAddress.IndexOf('>') - atIndex);
            }
            else
            {
                return emailAddress.Substring(atIndex + 1);
            }
        }

        public static IPAddress[] GetMailExchangeServer(string domainName)
        {
            IPHostEntry hostEntry = 
              DomainNameUtil.GetIPHostEntryForMailExchange(domainName);
            if (hostEntry.AddressList.Length > 0)
            {
                return hostEntry.AddressList;
            }
            else if (hostEntry.Aliases.Length > 0)
            {
                return System.Net.Dns.GetHostAddresses(hostEntry.Aliases[0]);
            }
            else
            {
                return null;
            }
        }
    }
}

The user interface is naive; multi-threading and message logging have not been done.

Points of interest

If you have a typo error in the sender email address or use a fake address, the email can still be sent, but this way, you can't expect the receiver to reply to you.

Some systems, e.g., SPF, will check if the sender's IP is declared as a domain name or not. This makes it unreliable to send the email to any address.

In addition, don't send spam emails using my tool or the underlying source code!

History

  • 2008-06-05 - Article submitted.
  • 2011-06-11 - Updated introduction text.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

Share

About the Author

Liu Junfeng
Architect YunCheDa Hangzhou
China China
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionEmail send failed Pin
Member 123284885-Apr-17 9:49
memberMember 123284885-Apr-17 9:49 
QuestionNot working for me Pin
Member 1271084630-Aug-16 8:52
memberMember 1271084630-Aug-16 8:52 
Questionanother alternative Pin
Jamil Hallal13-Feb-16 12:22
professionalJamil Hallal13-Feb-16 12:22 
PraiseGreat piece of code Pin
Daniel Hafner15-Nov-15 23:28
memberDaniel Hafner15-Nov-15 23:28 
QuestionThank You!!!! Pin
Member 1098908223-Jun-15 12:23
memberMember 1098908223-Jun-15 12:23 
QuestionI WANT THIS IN C++ Pin
Doctorr8-Jan-15 9:59
memberDoctorr8-Jan-15 9:59 
GeneralRe: I WANT THIS IN C++ Pin
PIEBALDconsult8-Jan-15 10:37
protectorPIEBALDconsult8-Jan-15 10:37 
GeneralRe: I WANT THIS IN C++ Pin
Doctorr9-Jan-15 4:49
memberDoctorr9-Jan-15 4:49 
GeneralRe: I WANT THIS IN C++ Pin
daluu7-Nov-15 15:33
memberdaluu7-Nov-15 15:33 
GeneralMy vote of 5 Pin
CoffeeShop7-Feb-14 4:13
memberCoffeeShop7-Feb-14 4:13 
GeneralMy vote of 5 Pin
AnsariAzam15-Aug-13 1:27
memberAnsariAzam15-Aug-13 1:27 
GeneralMy vote of 5 Pin
Prasad Khandekar23-May-13 20:01
professionalPrasad Khandekar23-May-13 20:01 
GeneralMy vote of 5 Pin
Polinia8-Mar-13 1:11
memberPolinia8-Mar-13 1:11 
GeneralMy vote of 3 Pin
buntheth22-Oct-12 20:23
memberbuntheth22-Oct-12 20:23 
GeneralRe: My vote of 3 Pin
gggustafson21-Jul-14 10:16
professionalgggustafson21-Jul-14 10:16 
GeneralMy vote of 5 Pin
adriancs15-Oct-12 0:51
memberadriancs15-Oct-12 0:51 
GeneralMy vote of 5 Pin
James Eager5-Jul-12 4:44
memberJames Eager5-Jul-12 4:44 
QuestionHi, you Pin
tesulakata5-May-12 22:58
membertesulakata5-May-12 22:58 
QuestionEmail Pin
michaeldexter26-Jul-11 16:14
membermichaeldexter26-Jul-11 16:14 
General我顶!!! Pin
xut244713-Jun-11 15:26
memberxut244713-Jun-11 15:26 
GeneralRe: 我顶!!! Pin
DaveAuld1-Jul-11 10:20
mentorDaveAuld1-Jul-11 10:20 
GeneralRe: 我顶!!! Pin
adriancs15-Oct-12 0:47
memberadriancs15-Oct-12 0:47 
GeneralRe: 我顶!!! Pin
DaveAuld15-Oct-12 0:49
mentorDaveAuld15-Oct-12 0:49 
GeneralRe: 我顶!!! Pin
RickyJiao10-Dec-12 20:43
memberRickyJiao10-Dec-12 20:43 
GeneralMy vote of 5 Pin
Wooters13-Jun-11 5:52
memberWooters13-Jun-11 5:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 12 Jun 2011
Article Copyright 2008 by Liu Junfeng
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid