Last active
November 18, 2020 14:20
-
-
Save timiles/ba930c196044e17d97b781566a8ff4f0 to your computer and use it in GitHub Desktop.
Generate and send random Secret Santa assignments via email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var santas = new[] | |
{ | |
// TODO: Fill out names and email addresses of all participants | |
new Santa("Person 1", "[email protected]"), | |
new Santa("Person 2", "[email protected]"), | |
new Santa("Person 3", "[email protected]"), | |
new Santa("Person 4", "[email protected]"), | |
}; | |
var shuffledIndexes = GenerateShuffledIndexes(santas.Length); | |
AssignRecipients(santas, shuffledIndexes); | |
SendEmails(santas); | |
} | |
int[] GenerateShuffledIndexes(int length) | |
{ | |
if (length <= 2) | |
{ | |
throw new Exception("Your Secret Santa isn't very secret, you need more friends!"); | |
} | |
int[] indexes; | |
do | |
{ | |
// OrderBy NewGuid is cheeky but it's good enough for this purpose | |
indexes = Enumerable.Range(0, length).OrderBy(x => Guid.NewGuid()).ToArray(); | |
} | |
// If any index maps onto itself, try again - you don't want to buy yourself a gift | |
while (indexes.Select((value, index) => value == index).Contains(true)); | |
return indexes; | |
} | |
void AssignRecipients(Santa[] santas, int[] recipientIndexes) | |
{ | |
for (var i = 0; i < santas.Length; i++) | |
{ | |
santas[i].RecipientName = santas[recipientIndexes[i]].Name; | |
} | |
} | |
void SendEmails(Santa[] santas) | |
{ | |
// TODO: Configure email account to send from. | |
// If you're using gmail, you may have to temporarily disable 2FA and enable "Less secure app access" | |
const string senderEmailAccount = "[email protected]"; | |
var client = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587) | |
{ | |
Credentials = new System.Net.NetworkCredential(senderEmailAccount, "password"), | |
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, | |
EnableSsl = true, | |
}; | |
foreach (var santa in santas) | |
{ | |
var subject = "π Your Secret Santa Assignment! π"; | |
var body = $@"Ho ho ho! Dear {santa.Name}, | |
You have been randomly assigned to buy a Secret Santa gift for.... | |
(π₯ drumroll please....) | |
{santa.RecipientName}! | |
βπ Merrrrrry Christmas! π¦π₯ | |
"; | |
client.Send(senderEmailAccount, santa.EmailAddress, subject, body); | |
} | |
} | |
class Santa | |
{ | |
internal Santa(string name, string emailAddress) | |
{ | |
this.Name = name; | |
this.EmailAddress = emailAddress; | |
} | |
internal string Name { get; } | |
internal string EmailAddress { get; } | |
internal string RecipientName { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment