Skip to content

Instantly share code, notes, and snippets.

@timiles
Last active November 18, 2020 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timiles/ba930c196044e17d97b781566a8ff4f0 to your computer and use it in GitHub Desktop.
Save timiles/ba930c196044e17d97b781566a8ff4f0 to your computer and use it in GitHub Desktop.
Generate and send random Secret Santa assignments via email
void Main()
{
var santas = new[]
{
// TODO: Fill out names and email addresses of all participants
new Santa("Person 1", "person1@example.com"),
new Santa("Person 2", "person2@example.com"),
new Santa("Person 3", "person3@example.com"),
new Santa("Person 4", "person4@example.com"),
};
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 = "example@gmail.com";
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