How to Send Mail Using Php Mailer.

1682
26232

In this post we will see that how we can send mail using Phpmailer. Before Start Tutorial we should know about what is Phpmailer , benefits of Phpmailer than we learn how to implement code for Php mailer.

what is Phpmailer

PHP Mailer is a code library to send emails safely and easily via PHP code from a web server.
phpmailer is a collection of classes which allows user to send mail via smtp seetings.
A user can easily configure php mailer according to his/her needs.

Benefits of Phpmailer over mail() function

php provides us mail() function allows us to send mails to user but it has certain limitations, mail() function send mail but it has very slow response ,mail() function does not assure the sending of mail.


On the other hand phpmailer assures the mail will be send to the user.
In this tutorial we will make 2 pages. first page is contact-us.php. in contact-us.php page we make a contact us form, where users query will be send via mail to admin.
Contact-us.php

Also Read :
PHP Login Script With Remember me.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript
Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
	$string = trim($string);
	$string = stripslashes($string);
	$string = htmlspecialchars($string);
	return $string;
}
if(isset($_POST["submit"]))
{
	if(empty($_POST["name"]))
	{
		$error .= '<p><label>Please Enter your Name</label></p>';
	}
	else
	{
		$name = clean_text($_POST["name"]);
		if(!preg_match("/^[a-zA-Z ]*$/",$name))
		{
			$error .= '<p><label>Only letters and white space allowed</label></p>';
		}
	}
	if(empty($_POST["email"]))
	{
		$error .= '<p><label>Please Enter your Email</label></p>';
	}
	else
	{
		$email = clean_text($_POST["email"]);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		{
			$error .= '<p><label>Invalid email format</label></p>';
		}
	}
	if(empty($_POST["subject"]))
	{
		$error .= '<p><label>Subject is required</label></p>';
	}
	else
	{
		$subject = clean_text($_POST["subject"]);
	}
	if(empty($_POST["message"]))
	{
		$error .= '<p><label>Message is required</label></p>';
	}
	else
	{
		$message = clean_text($_POST["message"]);
	}
	if($error == '')
	{
		require 'class/class.phpmailer.php';
		$mail = new PHPMailer;
		$mail->IsSMTP();								//Sets Mailer to send message using SMTP
		$mail->Host = 'localhost';		//Sets the SMTP hosts of your Email hosting, this for Godaddy
		$mail->Port = '25';								//Sets the default SMTP server port
		$mail->SMTPAuth = true;							//Sets SMTP authentication. Utilizes the Username and Password variables
		$mail->Username = 'your-email here';					//Sets SMTP username
		$mail->Password = 'password';					//Sets SMTP password
		$mail->SMTPSecure = '';							//Sets connection prefix. Options are "", "ssl" or "tls"
		$mail->From = $_POST["email"];					//Sets the From email address for the message
		$mail->FromName = $_POST["name"];				//Sets the From name of the message
		$mail->AddAddress('your email', 'Mainvps');		//Adds a "To" address
		//$mail->AddCC($_POST["email"], $_POST["name"]);	//Adds a "Cc" address
		$mail->WordWrap = 50;							//Sets word wrapping on the body of the message to a given number of characters
		$mail->IsHTML(true);							//Sets message type to HTML				
		$mail->Subject = $_POST["subject"];				//Sets the Subject of the message
		$mail->Body = $_POST["message"];				//An HTML or plain text message body
		if($mail->Send())								//Send an Email. Return true on success or false on error
		{
			$error = '<label>Thank you for contacting us</label>';
		}
		else
		{
			$error = '<label>There is an Error</label>';
		}
		$name = '';
		$email = '';
		$subject = '';
		$message = '';
	}
}
?>
<!DOCTYPE html>
<html>
	<head>
		<title>Send an Email on Form Submission using PHP with PHPMailer</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	</head>
	<body>
		<br />
		<div>
			<div>
				<div style="margin:0 auto; float:none;">
					<h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
					<br />
					<?php echo $error; ?>
					<form method="post">
						<div>
							<label>Enter Name</label>
							<input type="text" name="name" placeholder="Enter Name" value="<?php echo $name; ?>" />
						</div>
						<div>
							<label>Enter Email</label>
							<input type="text" name="email" placeholder="Enter Email" value="<?php echo $email; ?>" />
						</div>
						<div>
							<label>Enter Subject</label>
							<input type="text" name="subject" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
						</div>
						<div>
							<label>Enter Message</label>
							<textarea name="message" placeholder="Enter Message"><?php echo $message; ?></textarea>
						</div>
						<div align="center">
							<input type="submit" name="submit" value="Submit" />
						</div>
					</form>
				</div>
			</div>
		</div>
	</body>
</html>

1682 COMMENTS

  1. naturally like your web site however you need to take a look at the spelling on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth on the other hand I will surely come again again.

  2. What i do not understood is in reality how you’re not actually a lot more well-favored than you may be right now. You’re so intelligent. You realize therefore significantly in terms of this subject, made me individually believe it from so many various angles. Its like women and men don’t seem to be involved except it?¦s something to do with Woman gaga! Your personal stuffs great. All the time take care of it up!

  3. Howdy! This is my 1st comment here so I just wanted to give a quick shout out and say I genuinely enjoy
    reading your blog posts. Can you suggest any other blogs/websites/forums that deal with the same
    topics? Thanks for your time!

  4. por | feb 24, 2023 | Sin categoría | Este tipo de rondas son clave para alargar tu tiempo de juego por varios motivos. El más jugoso es que durante las mismas no estás pagando dinero así que estás teniendo oportunidades extra. Otra razón por la que te interesa conseguir rondas así es que el dinero de los premios siempre es mayor que en una ronda normal. Cada máquina tiene sus reglas y condiciones para conseguir bonificaciones. Si tienes dudas, lo habitual es que la propia tragaperras contenga un menú de ayuda que te indica qué pasos deberías seguir. App cantar bingo Para la ruleta casual, los apostadores pueden jugar a través del modo instantáneo o descargar la aplicación del casino. Conservative Financial Stewardship You Know and Trust
    https://zanderyzxu518451.blog-gold.com/24718016/ruleta-virtual
    Algunos bonos sin depósito solamente te piden que introduzcas un código especial o que utilices un cupón para desbloquearlos. Como con el resto de bonos de casino, los códigos de bono sin depósito no están ocultos ni son difíciles de encontrar. Verás que los promocionan en la página principal o en la página de bonos. Puede que incluso recibas los códigos por correo en la newsletter del casino. ¿Aún no tienes cuenta? Puedes reclamar un bono de casino sin depósito cuando crees una cuenta en el casino en línea específico que ofrece el bono. Después de completar el proceso de registro, puedes usar el código de bono sin depósito proporcionado para reclamar el bono y ganar dinero real. Pero recuerda que no podrás retirar tus ganancias hasta que cumplas con los requisitos de apuesta establecidos por el casino online de México. Si ganas dinero en línea con un bono, tendrás que cumplir con los requisitos de reproducción antes de poder solicitar el retiro. La mayoría de los web de apuestas en línea en México requerirán que realices un depósito antes de retirar el dinero tus ganancias.

  5. Everything said made a great deal of sense.
    But, think on this, suppose you typed a catchier post title?
    I am not suggesting your content is not solid., but suppose you added a title that makes people desire more?
    I mean How to Send Mail Using Php Mailer. | ShortLearner is kinda boring.
    You ought to look at Yahoo’s home page and note how they create news titles
    to get viewers to open the links. You might add a video or
    a picture or two to get readers interested about what
    you’ve written. Just my opinion, it could make your posts a little
    livelier.

  6. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my
    blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

  7. Hi there just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Ie.

    I’m not sure if this is a formatting issue or something to
    do with internet browser compatibility but I thought I’d post
    to let you know. The style and design look great though!
    Hope you get the issue fixed soon. Cheers

  8. Hi this is kinda of off topic but I was wondering if
    blogs use WYSIWYG editors or if you have to manually
    code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone
    with experience. Any help would be greatly appreciated!

  9. Just wish to say your article is as astonishing.
    The clearness in your put up is just great and i could think
    you are an expert in this subject. Well with your permission let me to snatch your feed to keep
    updated with approaching post. Thanks 1,000,000
    and please keep up the rewarding work.

  10. While prolonged QT has been previously noted to be associated with Takotsubo Cardiomyopathy, it has only been recognized a handful of times and this case presents a woman with severely prolonged QTc cialis tadalafil

  11. Thanks for your marvelous posting! I genuinely enjoyed reading it, you might be a great author.I will make sure to bookmark your blog and will come back from now on. I want to encourage one to continue your great writing, have a nice weekend!

  12. I am extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it’s rare to see a nice blog like this one nowadays.

  13. Il cliente dopo aver preso visione delle proprie carte può decidere se “rimanere” o “sviluppare” il gioco rispettando delle semplici regole: quando il punteggio raggiunto è inferiore o pari a 11 ha l’obbligo di superarlo chiamando almeno un’altra carta, quando arriva al 21 si deve fermare, in tutti gli altri casi la richiesta è libera; se però oltrepassa il 21 “sballa” e per quella mano non ha più la possibilità di rientrare in gioco. Cominciando dalla sua sinistra, postazione per postazione, il Dealer, leggendo il punteggio, inviterà ogni titolare a manifestare il suo gioco. La risposta dovrà essere inequivocabile: “carta” o “no carta”. Nel manuale, però, il discorso si fa molto più ampio. Parleremo delle differenze tra Blackjack classico ed europeo, di Expected Value, di Deck Penetration, di come valutare e scegliere sia il casinò sia addirittura il singolo tavolo da gioco, in funzione delle probabilità di vittoria che questi ci danno, insieme a molto, molto altro.
    http://oracos.com/en/bbs/board.php?bo_table=free&wr_id=18971
    Il bonus di benvenuto può assumere varie forme, come ad esempio un bonus sul deposito (una percentuale del tuo deposito viene aggiunta come bonus), scommesse gratuite, cashback sulle perdite e altro ancora. Queste offerte possono aumentare significativamente il tuo potenziale di scommessa e offrire ulteriori opportunità di vincita. I bonus scommesse senza deposito sono senza dubbio le offerte più ricercate online dagli amanti del betting. Con l’aumento progressivo dei giocatori che decidono di piazzare scommesse online anziché in agenzia, i bookmakers si impegnano sempre più per creare portali di gioco accattivanti e con le migliori promozioni. E un bonus senza deposito scommesse è uno dei modi più efficaci per attrarre nuovi utenti.

  14. New Jersey online casino bonuses are there to serve a purpose – it is to entice new players to join a site. They’re good for the casino because it attracts a new player, and they’re good for the player because they get an (often) generous bonus amount to play with on top of their bankroll. So, they get more funds to play with and, in turn, more shots at winning. Welcome bonuses are usually higher than regular NJ online casino promos for existing players. Just as its name says on the tin, online casino no deposit bonus codes provide rewards, such as free spins or bonus funds, to players without requiring a deposit to claim. Many no deposit casino bonuses also come with actual bonus codes attached, which often consist of random strings of letters and numbers that you enter into an online casino to redeem perks and prizes.
    http://010-9506-3279.withc.kr/bbs/board.php?bo_table=free&wr_id=28388
    Zynga Poker doesn’t allow the use of bots in games. Therefore, all the people you play against are real people. It’s also illegal to use an automation system. If you think someone is cheating, you can report it to the company. The stripped-deck variant was deployed earlier this month, “unlocked” by players reaching a certain level, as first reported by PokerNews this week. Technically speaking, Google TV’s support for Flash-based web sites means players can already play Texas HoldEm Poker and other Zynga games through the web browser. However, the new Google TV version announced today is “especially optimized for playing poker from the comfort of your own couch,” and easily controllable with the Google TV remote, Zynga said. To start using this program, simply download any selected Apps Installer. It will then install both the game and the wrapper system into your system, and create a shortcut on your desktop. Controls have been pre-defined in the current version for the time being, control setting varies per game.

  15. Hey There. I found your blog using msn. This is an extremely smartly written article. I will be sure to bookmark it and come back to read more of your useful information. Thank you for the post. I will definitely comeback.

  16. Is there a game that you love, but you can’t find on CrazyGames? Suggest a game to us and we’ll see what we can do to get it. You can also contact us for any general suggestions or improvements. Long before Forza Horizon, there was Test Drive Unlimited, which offered many of the same thrills. It offered up a large open world, constantly connected online multiplayer for impromptu road trips and the opportunity to loaf around in expensive supercars like you’ve just sold a Silicon Valley startup. This game is modelled around the basic principle of competing in championships to earn points and win prizes like many of the games here, except for one lethal rule: your opponents can pelt you with bullets throughout the races. This brutal twist, paired with the charming throwback graphics mean that Death Rally Classic offers hours of fun at no cost to you whatsoever.
    http://bycamping.co.kr/albino/bbs/board.php?bo_table=free&wr_id=13509
    The Mass Effect trilogy that released during the Xbox 360 era is beloved by gamers the world over thanks to its immersive role-playing gameplay and deep science fiction lore. And the romanceable aliens. Let’s be real. The Mass Effect Legendary Edition makes these games even better by significantly cleaning up all three with a number of visual, audio, and gameplay enhancements, bringing the series into the modern age while keeping our rose-colored memories of it completely intact.  While Final Fantasy XIV: A Realm Reborn is not the most recent entry in the Final Fantasy series, it is a finely tuned MMO that still regularly receives new updates and content. Allowing players to create characters of a variety of classes and races, players can team up to take on a massive variety of quests and bosses as they gain new equipment and skills. For those looking for a massive multiplayer RPG experience that constantly growing, A Realm Reborn may be for you!

  17. If you’re looking for a lucky clover, Irish Spins has it. Their website has a gorgeous green and bejewelled look to match the Irish theme and plenty of slots to entertain players. The site is well worth a try, supported by world-renowned software providers and with multiple customer support and payment options. With Bojoko, you never have to worry about the legality of the casinos and we make sure you can discover the highest quality sites. We also recommend checking out our more generic article and list of best slot sites that covers older and more established slot websites as well. Over the last few years, several new slot sites and casinos have been launching in the UK every single month, but the avalanche of new slots sites slowed down a bit last year and we expect this to continue during 2023.
    http://www.bwave.co.kr/bbs/board.php?bo_table=free&wr_id=26093
    There are some risks from playing at non-UK gambling sites that are not a licensed UKGC casino, and non-UK based. At these non-UK regulated sites players can not guarantee the safety of transactions since this type of online casino is independent. You must be aware of the disadvantages when gambling on one of these sites that accept players from the UK on non-UK casino sites. Popular games with frequent players from famous software providers are not available, like Netent casinos and Gamesys. Overall, you should also pay attention to a casino or game’s payout rate, and we would suggest looking elsewhere if the payout rate is less than 96%. As a rule of thumb, most online slots will offer around this percentage, and the best casino payout rates will be even higher. Some casino sites definitely offer better payout percentages than others, with the payout rate being as high as 99%. If this sounds too good to be true, sign up to Virgin Games Casino, where the RTP for most casino table games goes up to 99.64%!

  18. Apart from reviewing what a PokerStars Casino bonus, our experts also took a look at how this casino handles responsible gaming. Reload bonuses help online casinos ensure that new players keep playing. These bonuses reward players who continuously use their real money gaming accounts. Some reload bonuses provide a reward that matches your reload amount, while others are linked to specific payment methods such as e-wallets, crypto, and prepaid cards. Therefore, it’s vital always to find out the terms of any online casino’s reload bonus beforehand. All things considered, PokerStars Casino has a lot to offer especially when it comes to its rich gaming library which is regularly boosted with new titles. The casino is also home to one of the most rewarding loyalty programs that always delivers special bonuses and promotions for the most loyal customers. With this being said, we can only recommend visiting this venue for amazing online casino gaming sessions on mobile and desktop devices alike.
    http://somfriends.co.kr/bbs/board.php?bo_table=free&wr_id=11988
    Slots Empire Casino No Deposit Bonus 55 Free Spins Specialty Games at Slots Empire include the below Because no deposit bonuses have such low requirements, the casinos will generally impose a limit on the winnings that you can cash out. For example, you may win $150 with a $30 fixed cash bonus, but you can only cash out $100. Although you won’t find this limit on all no deposit bonuses, it is very common and is a way to make sure it’s worth it from the casino’s side to offer such kinds of bonuses. T&C: No Deposit Bonus is valid once for new customers only and has a maximum cashout x3 the bonus amount.The Wagering Requirements are x50 the bonus amount. The games included: Slots, Real-Series Video Slots, Keno, Scratch Cards, Board games. Tired to search every day for casino bonuses? Tired to see the word “expired” under every promotion? Do you are always looking for new online casinos? We have a solution. Subscribe to our newsletter and receive the latest casino bonuses, codes, exclusive deals, news and reviews directly in your mail.

  19. Nice post. I learn something new and challenging on blogs I stumbleupon everyday. It will always be exciting to read content from other writers and practice a little something from their sites.

  20. W naszym kasynie online znajdziesz szeroki wybór gier, które dostarczą Ci niezapomniane wrażenia. Idź Górnictwo dla klejnotów i poczuć dreszczyk kosmosu na pulpicie, gatunków i stylów gier w swojej gamie automatów. Dzięki mechanizmowi Xtra Reel Power możesz obstawiać mniej, nadal możesz grać w automat bitcoin w zaciszu swojej stałej lokalizacji. Pojęcie stare gry hazardowe za darmo obejmuje różne formy rozrywki, które opierają się na elementach losowości i ryzyka. Gry hazardowe są popularne zarówno w kasynach stacjonarnych, jak i w internecie. Wśród nich znajdują się gry karciane, takie jak poker, blackjack i baccarat, w których uczestnicy rywalizują o nagrody pieniężne lub rzeczowe. Oprócz tego istnieją także gry liczbowe, loterie, zakłady wzajemne oraz gry na automatach, które zapewniają szansę na wygraną. Ważne jest, aby pamiętać, że uczestnictwo w grach hazardowych wiąże się z ryzykiem utraty środków finansowych i wymaga odpowiedzialnego podejścia oraz świadomego podejmowania decyzji.
    http://www.kiel.co.kr/bbs/board.php?bo_table=free&wr_id=31674
    75 zł Zasady nie są skomplikowane, więc nawet po kilku rundach się w nich nie pogubicie. Nie ujęłam w liście TOP 10 tradycyjnych kart do gry (talia kart), jednak sięgamy po nie często, grając m.in. w: Makao, Wojnę czy Pana. A gdy chłopcy byli młodsi, bardzo często graliśmy z nimi w: Kim jestem?, Nogi Stonogi czy Grzybobranie (które są interesujące dla młodszych dzieci). Informujemy, iż nasz sklep internetowy wykorzystuje technologię plików cookies a jednocześnie nie zbiera w sposób automatyczny żadnych informacji, z wyjątkiem informacji zawartych w tych plikach (tzw. „ciasteczkach”). Siema Siema z tej strony Adix z BigBadDice :)Tak, to ja jestem tym Adixem 😉 Opisywanie Adixa nie ma sensu. Chcesz wiedzieć więcej, obejrzyj jakiś film na naszym kanale albo wpadnij na live i pogadajmy o grach, kotletach i życiu.

  21. I like the valuable information you provide in your articles. I will bookmark your weblog and check again here frequently. I am quite certain I will learn a lot of new stuff right here! Good luck for the next!

  22. Excellent blog here! Also your site a lot up fast! What host are you using? Can I am getting your associate link for your host? I want my site loaded up as fast as yours lol

  23. An impressive share! I have just forwarded this onto a friend who had been doing a little research on this. And he in fact bought me lunch because I found it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanx for spending time to discuss this issue here on your web page.

  24. Just desire to say your article is as surprising. The clarity
    in your post is simply excellent and i can assume you’re an expert on this
    subject. Fine with your permission allow me to grab your feed to keep
    up to date with forthcoming post. Thanks a million and please
    continue the enjoyable work.

  25. You’ve made some good points there. I looked on the internet to find out more about the issue and found most individuals will go along with your views on this site.

  26. The best thing about Gala Bingo, though, is its community. When you’re not playing any bingo games, you can pop over to the chat rooms and interact with other players and make new friends. The social side of bingo is, of course, one of the main reasons any of us play the games in the first place, and Gala Bingo has got it nailed.  Bingo Billy is also a great option for the Irish. This online bingo room always has weekly promotions for loyal users. The jackpots are also quite large, and Bingo Billy displays the current jackpots on their homepage. This should get you in the mood to play one of their many bingo games and take home a nice payout. It’s not often we get as excited about a bingo site as we do about bet365 bingo, and this is with good reason. Besides the top-notch app development which has paved the way for a sensational interface and crisp gaming visuals, it’s a site that truly gives you the feel of using an exceptional platform. With around 10 games starting every 5 minutes, including variations like Cash Cubes, Housey Bingo, and even Age of the Gods Bingo, the quality just never seems to end. Needless to say, you won’t be getting bored in a hurry, and the bet365 app won’t require you to break the bank to get involved either.
    http://goldenbeach7.com/bbs/board.php?bo_table=free&wr_id=131206
    Players can trust that the gameplay in Big Red Slot is fair and secure thanks to its use of an RNG to generate results. The software developer operates with proper licensing and also runs in-house tests on its games. Also, access Big Red in casinos with appropriate licenses of their own. Win real money after deposits to win cash prizes. Winning also depends on how combinations are made, make good use of features available to play in a trustful online casino. Registration involving personal data, payment methods, and withdrawal should be easy in a casino. There are no strategies for winning in the free Big Red pokie slot machine but on how to be a good player: Big Red isn’t a retro game as such, but it is an older online slot that is rather basic. It lacks many of the features you’d find on modern slots. That’s not necessarily an issue though, as you can find plenty of slot gamers that enjoy playing simpler games online today. Obviously too, any fan of anything to do with Australia, or particularly the wildlife you’ll find Down Under, will enjoy this slot.

  27. I will right away grasp your rss as I can not in finding your email subscription link or newsletter service. Do you have any? Please allow me understand so that I may subscribe. Thanks.

  28. what is the most reliable pharmacy in canada? : [url=https://slppharmacy.com/#]reputable online canadian pharmacy[/url] best canadian pharmacy online