Adding to the accepted answer, it would be a good idea to use repositories instead of the deprecated save method. Also added the customer notification after the tracking creation.
/** @var Magento\Sales\Model\Order\ShipmentRepository */
/** @var Magento\Shipping\Model\ShipmentNotifier */
/** @var Magento\Sales\Model\Order\Shipment\TrackFactory */
protected $_trackFactory; //missing ;
public function __construct(
$this->_shipmentNotifier = $shipmentNotifier;
$this->_shipmentRepository = $shipmentRepository;
$this->_trackFactory = $trackFactory;
public function addTrack($shipment, $carrierCode, $description, $trackingNumber)
/** Creating Tracking */
/** @var Track $track */
$track = $this->_trackFactory->create();
/* Notify the customer*/
Where $shipment is your shipment object. Notify will notify (send email) to the user and add a history item to the order status history collection.