Mailing items to players via C++

Good afternoon,

I am trying to send a simple mail message with attachment via custom script when a player levels, but I am having some trouble. Would someone mind sharing a method to send mail to a player via script? I cant find any working examples, I have been messing with this all day. Thanks in advance!

std::string subject = “header”;
std::string text = “content”;
uint32 receiverGUIDLow = receiver->GetGUID().GetCounter(); // can be from DB
uint32 senderGUIDLow = sender->GetGUID().GetCounter(); // can be 0
uint32 stationary = MAIL_STATIONERY_DEFAULT;
uint32 delay = 0;
uint32 money = 0;
uint32 cod = 0;
std::map<uint32 /entry/, uint32 /amount/> items = {
{25, 1},
{36, 1},
};

MailSender sender(MAIL_NORMAL, senderGUIDLow, (MailStationery)stationary);
MailDraft draft(subject, text);

if (cod)
draft.AddCOD(cod);
if (money)
draft.AddMoney(money);

SQLTransaction trans = CharacterDatabase.BeginTransaction();

ASSERT(items.size() <= MAX_MAIL_ITEMS);

for (auto& it : items)
{
uint32 entry = it.first;
uint32 amount = it.second;

ItemTemplate const* item_proto = sObjectMgr->GetItemTemplate(entry);
ASSERT(item_proto);
ASSERT(amount < 1 || (item_proto->MaxCount > 0 && amount > uint32(item_proto->MaxCount)));
if (Item* item = Item::CreateItem(entry, amount))
{
    item->SaveToDB(trans);
    draft.AddItem(item);
}

}

draft.SendMailTo(trans, MailReceiver(receiverGUIDLow), sender, MAIL_CHECK_MASK_NONE, delay);
CharacterDatabase.CommitTransaction(trans);

small example

Will try this out when I get home, thank you for the response!

Only having one issue, compiling on latest TrinityCore:

TrinityCore/src/server/scripts/Custom/custom_level_rewards.cpp:99:46: error: use of
undeclared identifier ‘eObjectMgr’
ItemTemplate const* item_proto = eObjectMgr->GetItemTemplate(entry);

I ended up getting this working https://github.com/oXL0C0Xo/TrinityCoreMods/blob/master/scripts/custom_level_rewards.cpp

The only problem I am having now, is that it does not update the players UI, or even have the mail in the mailbox until the player relogs.

Any help is appreciated!

It seems that if you use
MailReceiver(receiver)
instead of
MailReceiver(receiverGUIDLow)
where receiver is the player object itself, the mail is probably sent directly to the player that you set there.
Using guid causes the code to behave like the player is offline.

First off, thank you for your response, and help thus far! So making that change did indeed make the new mail notification show up, but when opening the mailbox, the mail is not there. If you relog your character, the mail will show up in the mailbox. Almost got it!

So it seems that the mail not showing up was only occurring on a gm character, as i leveled a non-gm, and the mail showed up right away.