I have been trying for several days to send emails in wordpress without using plugins. Using the wp_mail function I get error 500, before I used the mail function and it worked, but I have been recommended to use this, I have also read on the official wordpress page that it is the recommended one.
The mail.php file is located in the root directory of wordpress. This is my code:
Form->
<form method="post" action="<?php echo get_template_directory_uri(); ?>/php/processor.php" id="formulario">
<div class="form-group mb-3">
<input type="text" class="form-control" name="nombre" placeholder="Nombre" required>
</div>
<div class="form-group mt-3">
<input type="email" class="form-control" name="email" placeholder="Email" required>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="asunto" placeholder="Asunto" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="mensaje" rows="3" placeholder="Mensaje" required></textarea>
</div>
<div class="form-check mt-3">
<input type="checkbox" class="form-check-input" name="privacidad" required>
<label class="form-check-label">He leido y acepto la <a href="/politica-de-privacidad">política de privacidad</a></label>
</div>
<div class="col-md-12 mt-3">
<button type="submit" name="submitted" id="sendForm" class="button btn btn-primary btn-lg">Enviar mensaje</button>
</div>
</form>
mail.php->
<?php
require_once('../../../../wp-load.php');
if (isset($_POST['submitted'])) {
$nombre = $_POST['nombre'];
$email = $_POST['email'];
$asunto = $_POST['asunto'];
$mensaje = $_POST['mensaje'];
$from = '[email protected]';
$headers = array(
"Content-Type: text/html; charset=UTF-8",
"Sender: $email",
"From: Tuwebeconomica.es <$from>",
"Reply-To: $nombre <$email>"
);
// wp_mail($emailTo, $asunto, $body);
wp_mail($from, 'Nuevo mensaje de contacto desde tuweb.es', $body, $headers);
// Se redirecciona a la página de contacto
header('Location:' . getenv('HTTP_REFERER') . '?success=true');
}
As I said before I have tried the wp_mail function, mail, and phpmailer. I think I’m doing something wrong. Any help would be greatly appreciated. Thank you very much.
2
Answers
The problem wasn't the wp_mail() function, it was using it correctly. I missed importing the following line:
The question is corrected, maybe it can help someone else.
When looking for an answer like this, always look at the package docs first, which could have saved the time you wasted.
Though you can take on all of this yourself, this isn’t the best way to work with PHPMailer in WordPress. WordPress bundles PHPMailer, and you can make use of it instead of starting from scratch.
You need to write a hook function that intercepts the setup function that WordPress alley to configure its mailer. This lets you configure it as you like:
Once that is done, you can call the
wp_mail
function, and it will use your config instead of WordPress’ default settings.