Attach text string in mail using phpmailer

To attach a text string as a file using PHPMailer, you can use the addStringAttachment() method. Here's an example:

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->Subject = 'Test Email';

// Create a text string
$text = "This is a test email with a text string attachment.";

// Convert the text string to a file
$file = tempnam(sys_get_temp_dir(), 'text');
file_put_contents($file, $text);

// Attach the file
$mail->addStringAttachment($file, 'text.txt', 'text/plain');

$mail->send();

In this example, we create a text string using the $text variable, and then use the tempnam() function to create a temporary file on the server. We then use the file_put_contents() function to write the text string to the file.

Next, we use the addStringAttachment() method to attach the file to the email. We pass the file path, the file name, and the MIME type (text/plain) as arguments.

Finally, we send the email using the send() method.

Note that the addStringAttachment() method will automatically generate a file name and MIME type based on the file contents, so you don't need to specify these values explicitly. However, you can override these values by passing additional arguments to the method. For example:

$mail->addStringAttachment($file, 'my_text_file.txt', 'text/plain', 'UTF-8');

This would set the file name to my_text_file.txt, the MIME type to text/plain, and the character encoding to UTF-8.