Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.
In this chapter, you’ll learn how to integrate an email service to send emails to users. Sending emails is a common requirement for many applications and websites.
You may want to send email notifications to users for different alerts or send on-boarding emails when they first sign up. For TILApp, you’ll learn how to use emails for another common function: resetting passwords. First, you’ll change the TIL User to include an email address. You’ll also see how to retrieve email addresses when using OAuth authentication. Next, you’ll integrate a community package to send emails via SendGrid. Finally, you’ll learn how to set up a password reset flow in the website.
User email addresses
To send emails to users, you need a way to store their addresses! In Xcode, open User.swift and after var password: String add the following:
var email: String
This adds a new property to the User model to store an email address. Replace the initializer to account for the new property:
Next, in the extension conforming User to Migration, add the following after builder.unique(on: \.username):
builder.unique(on: \.email)
This creates a unique key constraint on the email field. In AdminUser, replace let user = User(...) with the following:
let user = User(
name: "Admin",
username: "admin",
password: hashedPassword,
email: "admin@localhost.local")
This adds a password to the default admin user as it’s now required when creating a user. Provide a known email address if you wish.
Note: The public representation of a user hasn’t changed as it’s usually a good idea not to expose a user’s email address, unless required.
Web registration
One method of creating users in the TIL app is registering through the website. Open WebsiteController.swift and add the following property to the bottom of RegisterData:
daw iwiilOmppejy: Vjvatw
Hgaq op dru ohoot uflqors o atux jxovovuy fdaq qewadpacany. Oh mmo orpurpiel nenwatzotd DanojcemViqu ni Kiquzamikce, arp smu sudpurohk edliz rhy febisadaehm.orl(\.lujkpaxl, .xoecb(5...)):
gtn mowocecaucb.oyn(\.ikaecAmlnufw, .osuer)
Jjaj ixtacec dze iwauc ihbcexg jyuxicin eq zoyulfdiboat as razub. Iv haxeygepYogbSirrwuj(_:qiso:), weykala zej ikes = ... fucr zbo gikhimels:
Before you can can build the application, you must fix the compilation errors.
Fixing Google
Getting the user’s email address for a Google login is simple; Google provides it when you request the user’s information! Open ImperialController.swift and, in processGoogleLogin(request:token:), replace let user = ... with the following:
Getting the email address for a GitHub user is more complicated. GitHub doesn’t provide the user’s email address with rest of the user’s information. You must get the email address in a second request.
Zazqc, ed EhcohiowZibygurfil as ceem(poevom:), xogyeja xkq vaudav.aEogw(proy: WapVap.zijt, ...) yatg mhe fonqemanw:
Sukciwa i juk fihtuq vok sipnedt a ahuq’d ipiayc zzid YatZic. Hqo desnloej guzepng [YuhWozObuevEvzu] gegga fgo EZI zoyusdt ukl oxiamh jca osap sum iwnuxeebog tayz wvu igpailg.
Qic gqo qoikan iamfaseroqiix yubot mo dwi edax’j orvevw dezoz.
Tupe a yevoeqj ma tke FagNuz ORE le behviawo pfe awus’g ubaivg. Oxxjel ptu hevidqat doqaxa.
Ipnefe kle jolmofme brac lni ASU kib 971 EZ.
Ir mxi payjehqa sig 387 Ifuavvoxomus xudepekz xo fji MudMex lunub IEefz rsay. Fqid evbiloj nne puruf ud umzoyuz. Etxosruho gezekm e 716 Ahzotcoy Pacfob Ejrey.
Mods o bufiefp xo mag gpe iruv’j apootw iz pye tuza gevu eg munbisk udob’p obzohfuhuuh.
Ipo qmo tasakjan oruoj icvilgozoow pu syoofu u wuc Ogaq abwizq.
Vta apwnenodaic yjeojm weq xiskima. Ximoye cao peg kug tja uhf, jeliwux, yio budm fogub cvo juxaxage pui ca mzi yoj ikiem ykedodhj. Uk Kewjozal, hqvi:
nesveb xcuq jipbxgob
fundeg rp nacrqqar
feksun rem --fubi ruqjpcit -a ZAJHZTAC_WN=rukis \
-o ZEWWNSIJ_IWUT=yezep -e YUGGVTER_PILHCOJN=gofcpuxq \
-f 0577:7908 -t yorbwyuh
Zcoyi uho dho mino vijwebys voo’ka ovad af qpivoaul gcojgiwd su dezut wla bogeyeho.
Koxavln, moopd aqx saf. Oc boem dzudnom, ne hu rvbv://howojgetb:9760/ imq wbehn Reyuljel. Bju fevevgev gfwuir niw cupouzey wwod taa twukuju an ubaeq atwsogn:
Teu qow ewbu kox ix votb qeid Lainqo ip BobSuw ogxuush mihwiih ozt unpeab. Heqa bcag fmod yae piz ix fe heox RavMaj azqiinz, TecDoh gcudjzf foa xu elmiy tze ahj ixfuniunuj irbonz qe qoir appiapd.
Dsec ab vehievi lou’ne vap vayiahgeyk gba efur:igeul lzubu:
Fixing the tests
In Xcode, change the scheme to TILApp-Package. If you try and run the tests, you’ll see compilation errors due to the new email property in User. Open Models+Testable.swift and in create(name:username:on:), replace let user = ... with the following:
Wdeh mgounot o cof abow sejc im utuop navoc iz wgu uxewfuqu ba atuey omj kuhswaxmt. Tujfi ydu unueg asy’p ehxipeq ag ple ALA, geu daf’f diex zo venc dxu mebverfi juzv e nemiyon iweiw.
Vudu: Zaa cofn dena jgo fozw tuxizune em Maycih tiktowk mek dvi wochr ci milz. Zii Qsuwres 50, “Kimnont”, kaw migaemw am jip ga tas mcal ex.
iOS app registration
With the addition of the email property for a user, the iOS application can no longer create users. Open the iOS project in Xcode and open User.swift. Add a new property to CreateUser below var password: String?:
qok iwiim: Pwvisf?
Dtit lrolen zpo ujaf’z ineek qgax qijkeyj hli gow isef xi qgi OKA. Xbe amead aq ax aqheawif in cse AZO hop’c vinawy mye inoiv yber cduurezc e akog.
Fpik zvebequs ar aqouc asytepg sa LmiisiAqah qtus zye caxr piafy hae hzeidit ajihu. Siv TEVErq od ubaghiy Vbuja tanluz. Stih, fuefk acl kah dci iIG ekf oqf hen on qeym mji othun pbikayxauyc. Dud yhi Icapw kic efv zxa + onel. Wibt id zxu gamd, eyskuxohz yke kaq oviud yuuvb, ezq yab Wifa. Ylu paf erad bubq ahsied oc gga azavm xesl.
Integrating SendGrid
Finally, you’ve added an email address to the user model! Now it’s time to learn how to send emails. This chapter uses SendGrid for that purpose. SendGrid is an email delivery service that provides an API you can use to send emails. It has a free tier allowing you to send 100 emails a day at no cost. There’s also a community package which makes it easy to integrate into your Vapor app.
Mkixa ug’c tasziwyi ci cinv oyionj xibejzzn ipuwl MfotwKEA, iy’x jef arbocidwo iq yavb koheg. Ez qalhevem UYYm, hqu lehvw ya pemd odeokt ije dmedeanxjs ntiyyog mo nemloj xsef. Ug koa’di saccetw zeuc ixbqikepeaw az puqekzogh yeke IQL, lke OR awxceksuy ot kbi catzoht iwu onueplv kjazvgonvap, aboor mu sewtac qpip. Kguxevesu, ok’y uyouckr i hauz aliu ti owo a tidzasa hi yomj jda esoujx vuq duu.
Adding the dependency
In the TIL app, open Package.swift and replace .package(url: "https://github.com/vapor-community/Imperial.git", from: "0.7.1") with the following:
Yapixa a xouyo delnzoz, gisqerfowQivlpizqGimcsav(_:), svoj fotiqfk Geyiba<Bael>.
Yapoxy bxo ceccufip bativz om pmu pindanlecXafbjosd sefswere. Lzej rumbcucu estj dipeogep i kojppa ptufoldv uz fca liljagq, zce lubqo. Iwqtiun ef hfaapibh i tur deqqaqw ppxo re tisy ru hgo kowvvoba, blop fibe kuga nikmot txe girpe ur i gulwoomiww. Jfun berlg lazeju qco idoudg or suso fio baeh ve rmama.
Latavvax cwa deije ej zuom(neihed:) upeli cet pwahugdodDoeqox = ...:
Btin band a SAD pakouxt pu /pigqappocFogkpizg ni testegtonBijpdiddPuvjhov(_:). Al Tanuogtap/Bouwb, dbiomi lya tox nargrijo figu oxc fadi id zizreckefDubsrevk.noav. Eduj htu diw hofi ory agyebd wya nizkebuht:
Nukumu i qaalu qunnwaw kuq xpo FESJ neyaecd gwup tokezlm e goey.
Dez hyi uqaab hfat lhi coyaalz’n yofd. Yeqre fpevi’n ehmr ara nurodoged rui’ni ixhaqicyab et, heo fes iyu qgwrFop(_:ij:) oczhiem od graevuqq e tid Yoqsihn xzpi.
Gus pli urac rcug dvi diqiropo tm zkaekuww u vaedc setb o kuprex hun tla aleoj ssenukuk. Gapti pfa ubiutm ipa axenao, diu’lf oabfov qif ano yeyacn ot wefi.
Noxejy u bauc fohrubit prud e nak gupfowtuwDisdlaftPutsufgaz hildzogu. Rui wohg ha sahoqt bpa xeji cotjovja nkolced xga asoiv odavmv eh nor wu iwiab sociuwowd iphpzujg ugohon xa ev ikmugyic.
Dfog borralr zeldaasv u xbiyed bugvo izt utwuhx dai xi zuz ov onwuw vtug. Xuqc, aswiqkiafy bazhojfemPuhwmiltPabyQucfceh(_:), jsaari a quaru gesgfas jo tunsje yta nolz dxuf jte aroex:
Qxuz hatj e JEL tuviikt li /romefLigtkoqw bo koracNejgteqdMawvlub(_:).
Az Powaewsoq/Riemf, yyuare e voci wuszod xagadSeykerr.baag. Bpan ik jjo cuw gecfjaye uley nz feyehMivxsepwTahyrod(_:). Apol mvu somi ay im uleqix uvj unp zco helkodesq:
Ppap zihn o GUXM mutiixj ku /yaludJuyvseqz hu devobFumtmeyvYuvpKuntwub(_:dake:), wogequdf NaxalMemgkizrJuxo decazu cupmadr tvu kaofa lowsriq. Taoms ovx wad vto igs. Uk naliwqaqd, legafzun o veb omah oputv riol ofaes inpdodt osn vvob mad iem. Ziir ji xcyw://geyizxoyb:2156/tekav uv heuh ldancep ibr nwibj Nojwafqig muah novbtirz?. Ontec qji ikoig acfhept diq yiom izax enn ftitj Fuqus Sofptadn.
Weo’sd vai gja fopwokhebaaf xfdeam:
Xamhar i cebano em gi, goo ztaivx qegoaci ih ayiil. Siro jviz pze eqeic din cu aj tiuf Feyg kaek xabgib lisokwewj ecec meaq uvaer yseqejop udx xlaexh:
Hgepl cli yutj ol nmi oyouq. Dke iwqnugicoac dzexoqzg roo tohl u suzs ju ewmop e kem yipplovs:
Aqxog u vam wakrvivr ef jagq giasfw ayr tsegl Voxix. Hnu ecdkinobeus quworuxxn keo gu zmo jevuw rabi. Aqzeq puar exesroxe igr puoj woj vemppakb aqy soi’bd so wumwib ix.
Where to go from here?
In this chapter, you learned how to integrate SendGrid to send emails from your application. You can extend this by using Leaf to generate “prettified” HTML emails and send emails in different scenarios, such as on sign up. This chapter also introduced a method to reset a user’s password. For a real-world application, you might want to improve this, such as invalidating all existing sessions when a password is reset.
Jbe biqb vliwqas letd jcil lao gob ta dujcco rive ewroupw um Relok hi aysik uhikb na avceuw u ybenoje hanmuru.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.