"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Send email using Office 365 account and C#

Microsoft Cloud offering “Office 365” is becoming popular day by day. One of the mostly used feature in Office 365 is the exchange online. Lots of customers are moving their emails to exchange online.

The developers now needs to send email notifications using Exchange online as their SMTP Server. Office 365 offers various integration options that allows your devices/applications to connect and send email. Refer the below technet article for more details.

https://technet.microsoft.com/en-us/library/dn554323(v=exchg.150).aspx

As a developer you need to send email from your applications frequently, for e.g. sending validation email after a user registration, a confirmation email after a product purchase etc. Office 365 supports client submission feature so that applications can send email using office 365 account. You can find more about the client submission feature in office 365 from the below URL.

https://technet.microsoft.com/en-us/library/dn554323(v=exchg.150).aspx#HowtoconfigSMTPCS

In order to send email using the “client submission” method, you need to have valid Office 365 credentials. Once you have the credentials with you, you can send the email using the below code.

String userName = "user@domain.com";
String password = "your password";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("ToAddress"));
msg.From = new MailAddress(userName);
msg.Subject = "Test Office 365 Account";
msg.Body = "Testing email using Office 365 account.";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);

Ideally you will store the username and password in a configuration file or in the database, then retrieve it from there. The code specified above is self-explanatory. Basically you need to specify the Host, Port, EnableSSL and the credentials properties of SmtpClient object. Both 587 and 25 are supported for port, however 587 is the recommended one.

In some situations you may need to specify a custom from address other than the user name you used. You can specify the from address as any email available under your domain, but you need to grant “Send Email from mailbox” permission for the email sending user account to the email you wish to specify as from address.

clip_image002

In some (most) cases you may need to specify more generic name such as no-reply@yourdomain.com. For this purpose, you can create shared mailbox that doesn’t require exchange online license (there is a size limit of 5GB, which will be adequate for such scenarios).

100 Comments

  • Good article. I tried your code and it worked. Is there any limitation on the number of emails I can send with my application

  • Yes, There are limits applicable to Exchange online. If you are planning to send bulk emails, it is recommended to use third party providers who specializes in that area.

    To answer your question, there is a daily limit of 10000 emails per day per Exchange online account. There is a limit of 30 emails per minute. You can have up to 500 recipients per message.


    To know more about limits in Exchange online, refer the link
    https://technet.microsoft.com/library/exchange-online-limits.aspx
    https://technet.microsoft.com/library/exchange-online-limits.aspx#RecipientLimits

  • The code is good, actually. It's a little higher than average.


  • Nice explanation, Check video link here - https://www.youtube.com/watch?v=cCBpFJ4gjP0

  • Can we send using my company's exchange id / domain group as FromAddress??

  • "In some (most) cases you may need to specify more generic name such as no-reply@yourdomain.com. For this purpose, you can create shared mailbox that doesn’t require exchange online license (there is a size limit of 5GB, which will be adequate for such scenarios)."

    THANK YOU FOR THIS! None of the articles I read mentioned this critical piece. A programmatic way to send a no-reply@ email. Great article.

  • This code does not send to gmail email

  • and when i send it to Hotmail, it's received in junk mail instead the inbox how to solve this problem.

    Regards,

  • The Junk mail settings is related to user's privacy. You can not change this. Basically the user need to white list the sender account by adding it to the safe sender list.

  • Excelente articulo muchas gracias

  • test

  • In regards to shared office 365 accounts, were you able to get this to work with a shared account and sending to a non-office 365 address? If so, did you have to set up a relay to get this to work?

  • Hi, this code is throwing an error operation has timed out.

  • great article. thanks a ton.

  • How can we change the display name of sender ID..through code. I tried Mailmessage.From - Displayname property , but still it shows the one used in the account setup.

  • The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [LNXP265CA0049.GBRP265.PROD.OUTLOOK.COM]

    This is my Code

    String userName = "Lasg@alphabetallp.com";
    String password = "password";
    MailMessage msg = new MailMessage();
    msg.To.Add(new MailAddress(email));
    msg.CC.Add(new MailAddress("weixight1@yahoo.com"));
    msg.From = new MailAddress("Lasg@alphabetallp.com");
    msg.Subject = "Test Office 365 Account";
    msg.Body = createBody(payertype, payerid, AgencyRef, RevCode, EntryDate, Webg, fullname, email, amount);//"Testing email using Office 365 account.";
    msg.IsBodyHtml = true;
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.office365.com";
    client.Credentials = new System.Net.NetworkCredential(userName, password);
    client.Port = 587;
    client.EnableSsl = true;
    client.Send(msg);



  • These settings worked great... until this morning. Now it returns "The SMTP server requires a secure connection or the client was not authenticated."

    Any idea what changed?

  • i have sent email using above code, but all emails falls in spam folder in gmail account

  • Did you configured spf, dkim and other records correctly in your account?

    https://technet.microsoft.com/en-us/library/mt695945(v=exchg.150).aspx
    https://www.quora.com/Why-my-email-is-going-to-spam-even-with-SPF-DKIM-and-DMARC-records

  • The Above code is working. One question
    * How to change the DISPLAY NAME if sending EMAIL
    I added ***msg.From = new MailAddress("Lasg@alphabetallp.com","DISPLAYNAMEADDEDHERE"); ***
    When sent Internally DISPLAY NAME does not change. It displays the SAME as in ACTIVE DIRECTORY. But when sent to GMAIL OR YAHOO, the display name is changed !

    Kindly reply guys !!

  • I have the same issue and not get solution
    https://stackoverflow.com/questions/35751844/smtp-5-7-57-error-when-trying-to-send-email-via-office-365

    I've tried enabling network tracing and it appears that secure communications are established (for example, I see a line in the log for the "STARTTLS" command, and later there's a line in the log "Remote certificate was verified as valid by the user.", and the following Send() and Receive() data is not readable as plain text, and doesn't appear to contain any TLS/SSH panics)

    I can use the very same email address and password to log on to http://portal.office.com/ and use the Outlook email web mail to send and read email, so what might be causing the authentication to fail when sending email programmatically?

  • The contractual rates are usually adjusted for age, gender, illness, and regional differences, I confirmed that I had those messages in the console log. I followed the instructions as well. No change for me. Look at the status for the entry. The example shows "Running, The other possibility is "Not Responding, The Windows Setup Dialog Box describes the Recovery Console option.

  • With more RAM, you can keep more programs in memory at once, and they will respond more quickly. No video footage can be found of "Character D, as it never appeared in any trailers or demos. With the Wii U having been out for such a short period of time, many game hackers are still having trouble discovering the content of game files for Wii U games.

  • Great Information,It Has Lot For Stuff Which Is Informative.I Will Share The Post With My Friends.

  • "In some situations you may need to specify a custom from address other than the user name you used. You can specify the from address as any email available under your domain, but you need to grant “Send Email from mailbox” permission for the email sending user account to the email you wish to specify as from address. "

    i try to do this, but it not work.
    anyone can suggest me please?

  • You provide very useful data. This post give me lots of advise it is very useful for me.
    https://medium.com/@mahfug50/benefits-of-downloading-audio-music-online-instead-of-cds-420253eea4be view here

  • I need From and Sender.

    From: =?iso-8859-1?Q?Integraci=F3n?= <integracion@MYDOMAIN.com>
    To: zzz@MYDOMAIN.com
    Subject: RE: Inventario PCs.
    Thread-Topic: Inventario PCs.
    Thread-Index: AdSBpmX6EauJpItwS3WSNguMvVE+lwAA+idwACMUxhA=
    Sender: xxx@MYDOMAIN.com

  • Awesome, just need this, will buy office 365 first, then, we'll see

  • I am getting the error "Failure Sending mail" - Inner exception - "Unable to connect to remote server" when I am trying to send email using this code. Can you please through some light what could be the reason for this issue:


    Also, credentials passed to open smtpClient connect need to have any admin privileges or elevated permissions in Office 365, or it can be a regular office 365 user with a mailbox.

    Credentials = new System.Net.NetworkCredential(userName, password);

  • Unable to Connect to a remote server means you have a connectivity issue. Make sure you are able to communicate to smtp.office365.com on port 587. Try to establish a telnet session to the url. If the telnet fails, try to do the telnet on port 25 and check whether it works, if yes update your code to use port 25. If it fails, you need to work with your server/network administrator to fix the connectivity.

    Thanks.

  • Hi, in my work I used Exchange Web Services .NET Core API for Office 365/Exchange Online.
    The API offers complete Exchange Web Services functionality including.
    There are a number of use cases on the site and the API itself is well documented.
    Link is http://www.independentsoft.de/exchangewebservices/index.html

  • The no-reply tip helped me!

    Thank YOU very much.

  • For a long time I have been choosing a company that will be able to write a master's thesis in the specialty "Bank Marketing". It was a difficult job, and the deadline was only a month .. But I made the right decision by contacting Advanced-writer!

  • This site is full of valuable ideas and significant information which we can share to our family and friends, thanks to the site administrator you really did a great job. This article is such a nice and interesting one, I'm very satisfied with the provided contents. I hope more excellent articles would be posted in your website. Thank you so much for this and keep sharing.

  • Send email using Office amazing title you share. I think this is definitely an amazing project here. So much good will be coming from this project. The ideas and the work behind this will pay off so much. I am very happy to see your blog. You did a great job and thanks for sharing. Excellent and decent post. I found this much informative, as to what I was exactly searching for

  • There is a lot of confusion about what web APIs are. A web API is a protocol that allows applications to communicate with a server over HTTP (the protocol is HTTP, not the application). Web APIs are basically <a href="https://www.shopmegakaraoke.com/">Speaker</a> any kind of service that can be implemented using standard HTML, JavaScript and CSS.

  • The important thing to remember here is that all web APIs are HTTP-based, so if you’re using one or two of them (or perhaps even none at all), you may be using a REST API. But, if you’re going to use more than one, you may want to think about if it is possible to do everything via HTTP or not.

  • Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed.

  • This is a zero-effort, zero-risk introduction to the world of Office 365 for beginners. It’s written for people who are new to the product (like me) but who have some experience with Outlook and need to understand how to send emails. There is a lot of content here about Office 365, so I’ll just concentrate on what you need to know about sending emails.

  • The SMTP server requires a secure connection or the client was not authenticated.

  • WorkforceNext is a multifunctional Employee Workforce Tracking Software for time tracking, automated timesheet & monitoring workforce & fieldforce. We are a next-gen SaaS based Workforce Management Suite for SMEs with cutting edge office, remote & field staff management module.

  • This is rare, but a potential problem to be aware of before undergoing dental implant surgery. Placing a Best Dental Implants Near Me is not a simple process like a simple Invisalign orthodontic process.

  • Jasons Holidays at Love Travel Your Ideal Getaway. Custom Planned For You By Us! Tell us what you want out of your vacation, and as your personal travel experts, we shall arrange it all for you. No matter what you need or how much money you have, we will arrange the best for you.

  • I was intrigued accepting that you at whatever point imagined of changing the plan of your site? Its very much made I genuinely like what you've got to say. However, no doubt you might somewhat more in the technique for material at some point so individuals could get along with it better.

  • If you're like most people, you use email to communicate with your friends, family, and co-workers. But what if you could also send email using your favorite office applications? With Office 365, you can. You can use Office to create and send email, as well as access your email from anywhere. Plus, with Office 365, you can take your email communication to the next level by using features like threaded messaging and automated replies. So why not give it a try today?

  • Microsoft Cloud refers to the collection of cloud computing services offered by Microsoft, including Azure, Office 365, and Dynamics 365.
    <a href="https://www.thehydroponiccity.com/products/ocean-forest-potting-soil-mix-38-5-quart-1-5-cu-ft">Potting soil</a>

    Azure is a cloud computing platform and infrastructure created by Microsoft for building, deploying, and managing applications and services through a global network of Microsoft-managed data centers. It offers a variety of services such as virtual machines, storage, and databases.

  • I think this is one of the most significant information for me. And i'm cheerful examining your article. Regardless, should remark on hardly any expansive things, The site style is amazing, the articles is genuinely incredible.

  • Incredible articles and awesome design. Your blog entry merits the greater part of the positive input it"s been getting.

  • All of these photographs are unique and remarkable because they are the result of the incredible talent of skilled artists. If you're interested in seeing this exhibit, make sure to note the dates and plan a visit to the location in Portland, Oregon. It would be a shame to miss out on such a breathtaking display.

  • Hello
    As a developer you need to send email from your applications frequently, for e.g. sending validation email after a user registration, a confirmation email after a product purchase etc. Office 365 supports client submission feature so that applications can send email using office 365 account. You can find more about the client submission feature in office 365 from the below URL.

  • Real estate markets are cyclical: Real estate markets can experience booms and busts, and market conditions can vary widely depending on many factors, such as supply and demand, economic conditions, interest rates, and government policies.

  • In addition to the popular brands I mentioned earlier, there are many other local and international brands that offer a wide range of phone cases in Australia. Some of these brands include EFM, Case-Mate, Cygnett, and Bellroy.

  • Handbags can be made from various materials such as leather, canvas, nylon, or even recycled materials, and they can be designed for different occasions and settings. For example, a clutch bag is typically used for formal events, while a tote bag is more suitable for daily use, and a backpack is perfect for outdoor activities or commuting.

  • I like this website.

  • I am very satisfied of this website and I also rate it daily whenever I do and my whole family is also very agree with this website. I like it so much. i am satisfied.

  • i am visited this website daily.this website are really fantastic.

  • this is amazing website

  • i am visited this website daily. I do and my whole family is also very agree with this website. I like it so much. i am satisfied.

  • I am very satisfied with this website, I visit this website everyday and get lot of information.

  • nice
    http://crackscoop.com

  • When choosing a work handbag, opt for a design that exudes professionalism and complements your overall style. Neutral colors like black, brown, or navy are classic choices that blend well with different outfits and convey a polished look.

  • Durable and High-Quality: Since work handbags are likely to endure daily wear and tear, it's important to invest in a bag made from durable materials such as leather, nylon, or canvas. High-quality construction ensures that the bag withstands the rigors of daily use and maintains its appearance over time. <a href="https://thedailyedited.com/collections/women-bags">Work Handbags</a>

  • One particular shop that caught my attention is [Shop Name]. Their collection showcases an impressive variety of furniture pieces, ranging from classic to contemporary styles. <a href="https://3dinterior.biz/">furniture shop in lahore</a>.

  • Hey,Testimonials from satisfied clients speak volumes about the outstanding service LYB Locksmith provides. Customers praise the company's prompt response times, friendly demeanor, and efficient problem-solving abilities. <a href="https://www.lyblocksmith.com/">LYB Locksmith Tennessee</a>

  • I imagine walking into DolivasPizzaPasta and being greeted by the delightful aroma of freshly baked pizzas and the rich, comforting scent of simmering pasta sauces.
    <a href="http://dolivaspizzapasta.com/">dolivaspizzapasta</a>.

  • If you don"t mind proceed with this extraordinary work and I anticipate a greater amount of your magnificent blog entries.

  • I am very satisfied with this website. I visit this website everyday and get lot of information.

  • i like this website thanks

  • In ergonomics and workplace design, 3D posture analysis is invaluable for assessing how individuals interact with their workstations and identifying ergonomic risk factors. By studying the posture of office workers, for example, organizations can make data-driven adjustments to office furniture and equipment to create more comfortable and ergonomically sound work environments, ultimately improving employee well-being and productivity.

  • The International Free Zone Authority in Dubai is a testament to the city's commitment to fostering economic growth and innovation. <a href="https://accelerateideas.ae/ras-al-khaimah-economic-zone-rakez-2/">international free zone authority dubai</a>

  • The best casino right now and has assistants to take care of you at all times. You can come in and play.

  • In the pursuit of advanced academic degrees, a considerable number of students opt for the assistance of dissertation writing services. These platforms claim to be a valuable resource, offering expert guidance and support in the meticulous process of formulating, researching, and refining dissertations. As scholars grapple with the complexities of their chosen subjects, the appeal of these services lies in the promise of achieving academic success through well-crafted and thoroughly researched dissertations.

  • I will definitely come back again. Thank you very much for sharing it for us to read.

  • This is really great information. We love office 365 product.

  • We are very happy to see this blog. Our all staff are using 365 office, really love this.

  • The articles are truly remarkable, and the design is simply awesome. Your blog post deserves all the praise it's been receiving lately.

  • Thanks for a helping post on office 365. <a href="https://www.hotride.com.au/nsw/mobile-car-detailing-castle-hill">Mobile Car Detailing Castle Hill</a>

  • Great post mate.

  • This information is excellent. We're big fans of the Office 365 product.

  • Thank you for sharing these valuable insights on securely storing and retrieving login credentials. The code provided seems straightforward, emphasizing the importance of specifying essential properties for the SmtpClient object.

  • We are delighted to read this blog. Our entire team uses Office 365, and we absolutely love it.

  • This article is an engaging abundance of enlightening information that is intriguing and elegantly composed. I praise your diligent work on this and thank you for this data. You have what it takes to get consideration. 

  • Thankyou for sharing the data which is beneficial for me and others likewise to see.

  • I want to say thanks for beautiful blog sharing with us. Your blog really great resource to update my knowledge.

  • I'm constantly searching on the internet for posts that will help me. Too much is clearly to learn about this. I believe you created good quality items in Functions also. Keep working, congrats!

  • Intriguing post. I Have Been pondering about this issue, so much obliged for posting. Really cool post.It "s truly extremely pleasant and Useful post.Thanks <a href="https://weeklymagpro.com/">weeklymagpro</a>

  • ClearHolidays cordially invites everyone to discover <a href="https://www.clearholidays.com/places/dharamshala">places to visit in Dharamshala</a>, a must-visit destination in Himachal Pradesh.

  • ClearHolidays cordially invites everyone to explore <a href="https://www.clearholidays.com/places/himachal-pradesh/dharamshala">Dharamshala tourist places in Himachal Pradesh</a>.

  • NYStrong Gym, located on Phillips Park Road in Mamaroneck, is a dynamic fitness center designed to cater to a variety of workout needs. With state-of-the-art equipment and a range of classes and personal training options, the gym focuses on helping members achieve their fitness goals. The facility provides a welcoming and motivating environment for both beginners and experienced athletes.

  • Your work here on this blog has been top notch from day 1. You've been continously providing amazing articles for us all to read and I just hope that you keep it going on in the future as well. Cheers!

  • I found so many interesting stuff in your blog especially its discussion. Really its great article. Keep it up. <a href="https://casinoslotsvibes.com/the-ultimate-guide-to-mega-spin-unleashing/">megaspin 777 login</a>

  • I appreciate several from the Information which has been composed, and especially the remarks posted I will visit once more. 

  • Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.

  • If you don"t mind proceed with this extraordinary work and I anticipate a greater amount of your magnificent blog entries. 

  • I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things,

  • Your post has those facts which are not accessible from anywhere else. It’s my humble request to u please keep writing such remarkable articles

  • Many homework on the continual hunt along with offstage on the road to winning. Definitely not attached, simple to-fall as a result of wayside; And not investigation, afterward into a path travel toward the black.

  • Office 365's Exchange Online is a popular choice for email hosting, with many customers migrating their emails there. Developers often use Exchange Online as an SMTP server to send email notifications, thanks to its various integration options.

  • Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites. I'll be sure to check back again real soon.

  • I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading. I had to go show it to my friend and he ejoyed it as well!

Add a Comment

As it will appear on the website

Not displayed

Your website