You can create a formula field for Case thread Id with formula as below:
"ref:_" &
LEFT( $Organization.Id , 5) &
IF (MID ( $Organization.Id, 6, 1) <> "0", RIGHT($Organization.Id,10),
IF (MID ( $Organization.Id, 7, 1) <> "0",RIGHT($Organization.Id, 9),
IF (MID ( $Organization.Id, 8, 1) <>"0", RIGHT($Organization.Id, 8),
IF (MID ( $Organization.Id, 9, 1)<> "0", RIGHT($Organization.Id, 7),
IF (MID ( $Organization.Id,10, 1) <> "0", RIGHT($Organization.Id, 6),
IF (MID ($Organization.Id, 11, 1) <> "0", RIGHT($Organization.Id, 5),
IF(MID ( $Organization.Id, 12, 1) <> "0", RIGHT($Organization.Id,4),
IF (MID ( $Organization.Id, 13, 1) <> "0",RIGHT($Organization.Id, 3),
IF (MID ( $Organization.Id, 14, 1) <>"0", RIGHT($Organization.Id, 2), "") ) ) ) ) ) ) ) )
& "._" &LEFT( Id, 5) &
IF(MID ( Id, 6, 1) <> "0", RIGHT(Id, 10),
IF (MID ( Id, 7, 1)<> "0", RIGHT(Id, 9),
IF (MID ( Id, 8, 1) <> "0", RIGHT(Id,8),
IF (MID ( Id, 9, 1) <> "0", RIGHT(Id, 7),
IF (MID ( Id, 10,1) <> "0", RIGHT(Id, 6),
IF (MID ( Id, 11, 1) <> "0",RIGHT(Id, 5),
IF (MID ( Id, 12, 1) <> "0", RIGHT(Id, 4),
IF (MID( Id, 13, 1) <> "0", RIGHT(Id, 3),
IF (MID ( Id, 14, 1) <>"0", RIGHT(Id, 2), "") ) ) ) ) ) ) ) ) & ":ref"
Then append this formula field in the subject line or email body in your apex class if you are generating them in the class. If you are using an email template, you can append the field directly in the email template using merged fields.
Hope this helps.