Start learning free

LESSON 112 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

Send an Email in C#

Practice

After a payment, the customer expects an email: "we got your money". A shop doesn't run its own mail server. It calls a mail service through its API, like the supplier and the payment provider. Ours lives at http://127.0.0.1:8003: you POST JSON with to, subject and body to /send, and it answers 202 Accepted, which means "I have it, I'll deliver it".

The email's text is built from pieces joined with +. In C#, when one side of + is a string, the other side is turned into text too, so numbers need no conversion:

var count = 3;
var text = "You have " + count + " new messages";
Console.WriteLine(text);   // You have 3 new messages

Put the email in its own method, so it has its own place and other code can send it too. The method is async and returns the mail service's answer, a Task<HttpResponseMessage>; until it has its return, C# refuses to compile it. Call it from the pay route only once the order is saved as paid: a declined card returns earlier, and so does a retry with the same idempotency key, so neither sends an email. The checker adds GET /check/sent, the list of emails the mail service received:

POST /orders/8/pay  (Idempotency-Key: 5f1d7c9e-…)  →  201  {"amount": 80, "order_id": 8, "payment_id": "pay_1"}
GET /check/sent  →  200  [{"body": "Hello Eva Rossi, we received your payment of 80. Thank you!", "id": 1, "subject": "Your order 8 is paid", "to": "eva@example.com"}]
POST /orders/8/pay  (the same key)  →  201  {"amount": 80, "order_id": 8, "payment_id": "pay_1"}
POST /orders/9/pay  →  402  {"error": "Payment declined", "reason": "card_declined"}
POST /orders/10/pay  →  201  {"amount": 21, "order_id": 10, "payment_id": "pay_2"}
GET /check/sent  →  200  [Eva's email, {"body": "Hello Chloe Ng, we received your payment of 21. Thank you!", "id": 2, "subject": "Your order 10 is paid", "to": "chloe@example.com"}]

Your task: add the variable MAIL, then write async Task<HttpResponseMessage> SendReceipt(int id): it finds the order and its customer, builds the subject and the body, and returns the awaited POST of them to MAIL + "/send". In the pay route, await it right after the UPDATE's cmd.ExecuteNonQuery();.


Assignment
Follow the Coding Tutorial to write the SendReceipt method and send a receipt after each successful payment.


Hint
The order has a customer_id; the name and the email are in the customers table, and a reader on that row gives customer["name"] and customer["email"]. The code won't compile until SendReceipt has its return. A method runs only when it's called: until the pay route calls it, GET /check/sent stays empty.


STEP 1 OF 11
    Ctrl + Enter to check

    Mail Order Email in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free